react之基于@reduxjs/toolkit使用react-redux
一、配置基础环境
npx create-react-app react-redux
2.安装@reduxjs/toolkit react-redux
npm i @reduxjs/toolkit react-redux
npm start
4.创建store文件
modules存储子store模块index.js组合modules中所有子模块,并导出store


二、使用React Toolkit 创建 counterStore
nodules目录下counterStore.js
import { createSlice } from '@reduxjs/toolkit'
const counterStore = createSlice({
name: 'counter',
initialState: {
count: 0,
},
reducers: {
addFn(state) {
state.count++
},
delFn(state) {
state.count--
},
},
})
const { addFn, delFn } = counterStore.actions
const reducer = counterStore.reducer
export { addFn, delFn }
export default reducer
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './modules/counterStore'
const store = configureStore({
reducer: {
counter: counterReducer,
},
})
export default store
三、为React注入store
import store from './store'
import { Provider } from 'react-redux'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Provider store={store}>
<App></App>
</Provider>
)
四、React组件使用store中的数据
import { useSelector, useDispatch } from 'react-redux'
import { addFn, delFn } from './store/modules/counterStore'
function App() {
const { count } = useSelector((state) => state.counter)
const dispatch = useDispatch()
return (
<div className="App">
<button onClick={() => dispatch(delFn())}>-</button>
{count}
<button onClick={() => dispatch(addFn())}>+</button>
<ul></ul>
</div>
)
}
export default App
五、实现效果

六、提交action传递参数

七、异步状态操作
1.modules目录下channelStore.js
import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
const listStore = createSlice({
name: 'list',
initialState: {
list: [],
},
reducers: {
setList(state, action) {
state.list = action.payload
},
},
})
const { setList } = listStore.actions
const getList = () => {
return async (dispatch) => {
const res = await axios.get('接口地址')
dispatch(setList(res.data.data.channels))
}
}
const reducer = listStore.reducer
export { getList }
export default reducer
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './modules/counterStore'
import listReducer from './modules/channelStore'
const store = configureStore({
reducer: {
counter: counterReducer,
list: listReducer,
},
})
export default store
import { useSelector, useDispatch } from 'react-redux'
import { useEffect } from 'react'
import { getList } from './store/modules/channelStore'
function App() {
const dispatch = useDispatch()
useEffect(() => {
dispatch(getList())
}, [dispatch])
const { list } = useSelector((state) => state.list)
return (
<div className="App">
<ul>
{list.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
)
}
export default App