1、安装redux @reduxjs/toolkit
npm install @reduxjs/toolkit redux -S
2、在src目录下创建store文件夹,创建index.js
import { configureStore } from "@reduxjs/toolkit";
import demo from "./modules/demoStore";
const store = configureStore({
reducer: {
demo: demo
}
})
export default store
3、在store文件夹下创建modules文件夹,创建demoStore.js
import { createSlice } from "@reduxjs/toolkit";
const demoStore = createSlice({
name: 'demo',
initialState: {
msg: 'hello'
},
reducers: {
setMsg: (state, action) => {
state.msg = action.payload;
}
}
})
export const { setMsg } = demoStore.actions;
const demo = demoStore.reducer;
export default demo;
4、在App.js中引入store实例
import store from "./store";
import { Provider } from "react-redux";
<Provider store={store}>
<App/>
</Provider>
5、在Demo组件中引入store实例
import { useSelector, useDispatch } from "react-redux";
import { setMsg } from "../store/modules/demoStore"
const Demo = () => {
const dispatch = useDispatch();
const { msg } = useSelector(state => state.demo);
const getMsg = () => {
return async (dispatch) => {
const res = await axios.get('http://localhost:3001/msg')
console.log('res === ', res.data.data)
dispatch(setMsg(res.data.data))
}
}
useEffect(() => {
getMsg(getList())
}, [dispatch])
return (
<div>
{/* 展示数据 */}
<h1>{msg}</h1>
{/* 数据更新,简单同步更新 */}
<button onClick={() => setMsg('redux')}>set</button>
</div>
)
}
export default Demo;