一、Redux与React-提交action传参
需求:组件中有两个按钮,点击add to 10和add to 20将count的值修改到对应的数字,目标count值是在组件中传递过去的,需要提交action的时候传递参数
实现思路:在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上
import { createSlice } from '@reduxjs/toolkit'const counterStore = createSlice({name: 'counter',// 状态初始数据initialState: {count: 0},// 修改数据的同步方法reducers: {increment(state) {state.count++},decrement(state) {state.count--},addToNum(state,action){state.count=action.payload}}
})// 结构出创建action对象的函数(actionCreater)
const { increment, decrement,addToNum } = counterStore.actions
// 获取reducer函数
const createReducer = counterStore.reducer
// 导出创建action对象的函数和reducer函数
export {increment,decrement,addToNum}
export default counterStore
counterStore.js
import { useSelector, useDispatch } from 'react-redux'
// 导入创建action对象的方法
import { addToNum, decrement, increment } from "./store/modules/counterStore";function App() {const { count } = useSelector(state => state.counter)// 得到dispatch函数const dispatch = useDispatch()return (<div className="App">{/* 使用dispatch提交action对象 */}<button onClick={() => dispatch(addToNum(10))}>add to 10</button><span>{count}</span><button onClick={() => dispatch(addToNum(20))}>add to 20</button></div>)
}
App.js
乍一看这个和pinia怎么这么像呢,就是将新值赋值给变量,下面放出pinia的实现做对比
import {defineStore} from "pinia"
import { ref } from "vue"export const select_components_store=defineStore('select_components',()=>{let now_components=ref("")function update_now_components(newVal){now_components.value=newVal}return {now_components,update_now_components}
})
piniaStore.js
二、Redux与React-异步状态操作
2.1、创建store的写法保持不变,配置好同步修改状态的方法
import { createReducer, createSlice } from "@reduxjs/toolkit";const channelStore = createSlice({name: 'channel',initialState: {channelList: []},reducers: {setChannels(state, action) {state.channelList = action.payload}}
})
channelStore.js
2.2、单独封装一个函数,在函数内部return一个新函数
在新函数中封装异步请求获取数据,调用同步actionCreater传入异步数据生成一个action对象,并使用dispatch提交
// 异步请求部分
const {setChannels}=channelStore.actions
const fetchChannlList = () => {return async(dispatch) => {const res = await axios.get('url')dispatch(setChannels(res))}
}const reducer = channelStore.reducerexport {fetchChannlList}export default reducer
channelStore.js
在入口文件中组合
import {configureStore} from "@reduxjs/toolkit"import counterStore from "./modules/counterStore"
import channelStore from "./modules/channelStore"// 创建根store组合子模块
const store = configureStore({reducer:{counter:counterStore,channel:channelStore}
})export default store
index.js
2.3、组件中dispatch的写法保持不变
import { fetchChannlList } from "./store/modules/channelStore";
function App() {const { channelList } = useSelector(state => state.channel)// 得到dispatch函数const dispatch = useDispatch()// 使用useEffect触发异步请求执行useEffect(() => {dispatch(fetchChannlList())}, [dispatch])return (<div className="App"><ul>{channelList.map(item => <li key={item.id}>{item.name}</li>)}</ul></div>)
}
App.js
下一章:ReactRouter01