背景:
JavaScript需要管理的状态越来越多,越来越复杂;这些状态包括服务器返回的数据、缓存数据、用户操作产生的数据等等,也包括一些UI的状态,比如某些元素是否被选中,是否显示加载动效,当前分页。
状态之间相互会存在依赖,一个状态的变化会引起另一个状态的变化,View页面也有可能会引起状态的变化;当应用程序复杂时,state在什么时候,因为什么原因而发生了变化,发生了怎么样的变化,会变得非常难以控制和追踪。
无论是组件定义自己的state,还是组件之间的通信通过props进行传递; 也包括通过Context进行数据之间的共享;React主要负责帮助我们管理视图,state如何维护最终还是我们自己来决定。
官网:
网址:
https://cn.redux.js.org/introduction/getting-started
手画图解:
准备工作:
安装Redux Toolkit 与 react-redx:
npm install @reduxjs/toolkit react-redux
实现counter:
ka.js:
import { createSlice } from '@reduxjs/toolkit'
import http from '../../utils/http'
const kaSlice = createSlice({
name: 'ka',
initialState: {
billList: [],
},
reducers: {
setBillList (state, action) {
state.billList = action.payload
},
addBill (state, action) {
state.billList.push(action.payload)
}
}
})
// 记一笔
const { addBill } = kaSlice.actions
const createBill = (data) => {
return async (dispatch) => {
const res = await http.post('/ka', data)
dispatch(addBill(res.data))
}
}
// 获取
const { setBillList } = kaSlice.actions
const getBills = () => {
return async (dispatch) => {
const res = await http.get('/ka')
dispatch(setBillList(res.data))
}
}
export default kaSlice.reducer
export {
createBill,
getBills
}
//解构actionCreater函数
const { inscrement, decrement } = counterStore.actions
//获取reducer
const reducer = counterStore.reducer
//导出
export { inscrement, decrement }
export default reducer
store/index:
import { configureStore } from '@reduxjs/toolkit'
import ka from './slices/ka'
const store = configureStore({
reducer: {
ka,
},
})
export default store
index:
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from 'react-router-dom'
import router from './router'
import './index.css'
import { Provider } from 'react-redux'
import store from './store'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
)
组件中使用store的数据:
useSelector把store的数据映射到组件中去
useDispatch通过action提交对象的dispatch函数
import { useSelector,useDispatch } from 'react-redux'
import { createBill } from '@/store/slices/ka'
const AppComponent= () => {
const dispatch = useDispatch()
const { billList} = useSelector(state => state.billList)
const saveBill = async () => {
const data = {}
await dispatch(createBill(data))
}
return (
<Button className="btn save" onClick={() => saveBill()}>保 存</Button>
}
}
export default AppComponent
dispatch提交action传参,可以携带参数过去!: