一、同步actions
1.概念
说明:在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,数会被传递到action对象payload属性上。
2.reducers对象
说明:声明函数同时接受参数
const counterStore=createSlice({
name:"counter",
// 初始化状态
initialState:{
count:0
},
// 修改状态的方法 同步方法
reducers:{
addToNum(state,action){
state.count+=action.payload
}
}
})
// 解构actionCreater函数
const {addToNum}= counterStore.actions
// 获取reducer
const reducer=counterStore.reducer
// 按需导出actionCreator
export {addToNum}
// 以默认导出的方式导出reducer
export default reducer
3.app.js
说明: 导入函数进行调用。
import { useDispatch, useSelector } from "react-redux";
import {addToNum} from "./store/modules/counterStore"
function App() {
const {count}=useSelector(state=>state.counter)
const dispatch=useDispatch()
return (
<div className="App">
<button onClick={()=>dispatch(addToNum(10))}>add To 10</button>
</div>
);
}
export default App;
二、异步actions
1.channelStore.js
import {createSlice} from "@reduxjs/toolkit"
import axios from 'axios'
// 1.创建store写法保持不见,配置好同步修改状态的方法
const channelStore= createSlice({
name:'channel',
initialState:{
channelList:[]
},
reducers:{
setChannels(state,action){
state.channelList=action.payload
}
}
})
// 异步请求
const {setChannels}=channelStore.actions
const fetchChannelList=()=>{
return async(dispatch)=>{
await axios.get('https://st2msh.laf.run/react_get_list').then(res=>{
dispatch(setChannels(res.data))
}).catch(err=>{
console.log(err);
})
}
}
export {fetchChannelList}
const reducer=channelStore.reducer
export default reducer
2. index.js
import { configureStore} from "@reduxjs/toolkit"
// 导入子模块reducer
import counterReducer from "./modules/counterStore"
import channelReducer from "./modules/channelStore"
const store=configureStore({
reducer:{
counter:counterReducer,
channel:channelReducer
}
})
export default store
3.app.js
import { useDispatch, useSelector } from "react-redux";
import {inscrement,decrement,addToNum} from "./store/modules/counterStore"
import {fetchChannelList} from "./store/modules/channelStore"
import { useEffect } from "react";
function App() {
const {count}=useSelector(state=>state.counter)
const {channelList}=useSelector(state=>state.channel)
const dispatch=useDispatch()
useEffect(()=>{
dispatch(fetchChannelList())
},[dispatch])
return (
<div className="App">
{count}
<button onClick={()=>dispatch(inscrement())}>+</button>
<button onClick={()=>dispatch(decrement())}>-</button>
<button onClick={()=>dispatch(addToNum(10))}>add To 10</button>
<ul>
{channelList.map(item=><li key={item.id}>{item.name}</li>)}
</ul>
</div>
);
}
export default App;
4.效果展示