react-redux与toolkitIndex使用

 

1.安装 React-Redux:首先,你需要将 React-Redux 安装到你的项目中。你可以使用 npm 或者 yarn 来安装它:

npm install react-redux

 

2.创建 Redux Store:在你的应用程序中,创建 Redux store 来管理应用程序的状态。你可以使用legacy_createStore函数来创建 Redux store。

import { legacy_createStore, combineReducers } from 'redux';
let store = legacy_createStore(reducer)
export default store

 

3.将Redux Store 与 React 应用程序集成:使用 Provider 组件将 Redux store 提供给 React 应用程序的其他组件。Provider 组件通常在应用程序的最顶层进行渲染,确保所有的子组件都可以访问到 Redux store。

import store from './store'
import { Provider } from 'react-redux'
        <Provider store={store}>
            <App />
        </Provider>

 

4.连接 React 组件与 Redux Store:使用 connect 函数来连接 React 组件与 Redux store。这样可以让你的 React 组件能够访问 Redux store 中的状态,并且可以通过派发 action 来修改状态。

// connect一般用于class
import { connect } from 'react-redux'
// connect 第一个参数state的映射,把需要的state映射到组件的props里去
// connect 第二个参数方法映射,把需要的方法映射到组件的props里去
export default connect(
    (state) => {
        // console.log(state)
        return {
            msg: state.mesReducer.msg,
            num: state.numReducer.num,
        }
    },
    (dispatch) => {
        console.log(dispatch)
        return {
            // react-reddux
            changeMsg() {
                dispatch({
                    type: 'changeMsg',
                    payload: 'world',
                })
            },
            changeNum() {
                dispatch({
                    type: 'add',
                })
            },
        }
    }
)(App)

 

5.创建 Redux Reducers:编写 Redux reducers 来定义应用程序状态的变化。Reducers 接收 action 并根据 action 的类型来更新状态。

import { legacy_createStore, combineReducers } from 'redux'

function mesReducer(state = { msg: 'msg' }, action) {
    // 具体修改数据的行为
    switch (action.type) {
        case 'changeMsg':
            state.msg = action.payload
            return { ...state }
        case 'restMsg':
            state.msg = 'hello'
            return { ...state }
        default:
            return state
    }
}
function numReducer(state = { num: 0 }, action) {
    // 具体修改数据的行为
    switch (action.type) {
        case 'add':
            state.num += 1
            return { ...state }
        default:
            return state
    }
}
// 分模块
let reducer = combineReducers({
    mesReducer,
    numReducer,
})
let store = legacy_createStore(reducer)
export default store

 

6.派发 Action:在你的应用程序中,使用 dispatch 方法来派发 action。派发 action 后,Redux 会自动调用相应的 reducers 来更新状态。

props.changeMsg()

 

完整代码:

index

import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import App from './App'
// import App from './App2'
import reportWebVitals from './reportWebVitals'
import store from './store'
// import store from './store/toolkitIndex'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </React.StrictMode>
)

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals()

 

store/index

import { legacy_createStore, combineReducers } from 'redux'

function mesReducer(state = { msg: 'msg' }, action) {
    // 具体修改数据的行为
    switch (action.type) {
        case 'changeMsg':
            state.msg = action.payload
            return { ...state }
        case 'restMsg':
            state.msg = 'hello'
            return { ...state }
        default:
            return state
    }
}
function numReducer(state = { num: 0 }, action) {
    // 具体修改数据的行为
    switch (action.type) {
        case 'add':
            state.num += 1
            return { ...state }
        default:
            return state
    }
}
// 分模块
let reducer = combineReducers({
    mesReducer,
    numReducer,
})
let store = legacy_createStore(reducer)
export default store

 

app

import logo from './logo.svg'
import './App.css'
// import store from './store'
// let state = store.getState().mesReducer
// connect一般用于class
import { connect } from 'react-redux'
import { changeMsg, add } from './store/toolkitIndex'
function App(props) {
    console.log(props)
    return (
        <div className="App">
            {/* <div>{state.msg}</div>
            <button
                onClick={() => {
                    store.dispatch({
                        type: 'changeMsg',
                        payload: 'world',
                    })
                    console.log(state)
                }}
            >
                修改redux
            </button> */}
            <div>redux只是单纯的js库,无法实时更新视图</div>
            <div>react-redux把数据/方法放在props里去响应</div>
            <div>{props.msg}</div>
            <button
                onClick={() => {
                    // props.dispatch({
                    //   type: 'changeMsg',
                    //   payload: 'world',
                    // })
                    props.changeMsg()
                }}
            >
                修改react-redux
            </button>
            <div>{props.num}</div>
            <button
                onClick={() => {
                    props.changeNum()
                }}
            >
                修改react-redux
            </button>
        </div>
    )
}
// connect 第一个参数state的映射,把需要的state映射到组件的props里去
// connect 第二个参数方法映射,把需要的方法映射到组件的props里去
export default connect(
    (state) => {
        // console.log(state)
        return {
            msg: state.mesReducer.msg,
            num: state.numReducer.num,
        }
    },
    (dispatch) => {
        console.log(dispatch)
        return {
            // react-reddux
            changeMsg() {
                dispatch({
                    type: 'changeMsg',
                    payload: 'world',
                })
            },
            changeNum() {
                dispatch({
                    type: 'add',
                })
            },
            // reduxjs/toolkit
            // changeMsg() {
            //     dispatch(changeMsg('world'))
            // },
            // changeNum() {
            //     dispatch(add())
            // },
        }
    }
)(App)

 

 

toolkitIndex使用与react-redux差异

1.Provider的store改成toolkitIndex的

2.hook(useSelector, useDispatch)方式只能用于toolkit,只能用于函数组件


toolkitIndex

import { createSlice, configureStore, createAsyncThunk } from '@reduxjs/toolkit'
// 处理异步
// 第一个参数 名字
// 第二个具体异步
export let changesNumThunk = createAsyncThunk(
    'numSlice/changesNumThunk',
    async (params) => {
        console.log(params)
        return await new Promise((reslove) => {
            setTimeout(() => {
                reslove(100)
            }, 1000)
        })
    }
)
let mesSlice = createSlice({
    name: 'mesSlice',
    initialState: {
        msg: 'hello',
    },
    reducers: {
        changeMsg(state, action) {
            state.msg = action.payload
        },
    },
})
let numSlice = createSlice({
    name: 'numSlice',
    initialState: {
        num: 0,
    },
    reducers: {
        add(state, action) {
            state.num += 1
        },
        // changeNum(state, action) {
        //     setTimeout(() => {
        //         state.num += 100
        //     }, 1000)
        // },
    },
    extraReducers: (chunk) => {
        chunk.addCase(changesNumThunk.pending, () => {
            console.log('pending')
        }).addCase(changesNumThunk.fulfilled, (state, action) => {
            state.num = action.payload
        })
    },
})
let store = configureStore({
    reducer: {
        mesReducer: mesSlice.reducer,
        numReducer: numSlice.reducer,
    },
})
export let { changeMsg } = mesSlice.actions
export let { add } = numSlice.actions
export default store

 

app2

// hook方式只能用于toolkit,只能用于函数组件
import { useSelector, useDispatch } from 'react-redux'
import { changeMsg, add, changesNumThunk } from './store/toolkitIndex'
function App2() {
    let num = useSelector((state) => {
        return state.numReducer.num
    })
  let msg = useSelector((state) => {
        return state.mesReducer.msg 
    })
  let dispatch=useDispatch();
    return (
        <div>
            <div>app2</div>
            <div>{num}</div>
            <button
                onClick={() => {
                    dispatch(add())
                }}
            >
                修改react-redux
            </button>
      <button
                onClick={() => {
                    dispatch(changesNumThunk(123))
                }}
            >
                异步修改react-redux
            </button>
      <div>{msg}</div>
            <button
                onClick={() => {
                    dispatch(changeMsg('world'))
                }}
            >
                修改react-redux
            </button>
        </div>
    )
}
export default App2

 

posted on 2024-04-08 22:27  sss大辉  阅读(26)  评论(0编辑  收藏  举报

导航