安装 npm install @reduxjs/toolkit
1.创建一个名为counterSlice.js
的文件,用于处理计数器模块的状态:
javascript
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment(state) {
state.value += 1;
},
decrement(state) {
state.value -= 1;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
2.创建一个名为userSlice.js
的文件,用于处理用户信息模块的状态:
javascript
import { createSlice } from '@reduxjs/toolkit';
const userSlice = createSlice({
name: 'user',
initialState: {
name: '',
age: null,
},
reducers: {
setName(state, action) {
state.name = action.payload;
},
setAge(state, action) {
state.age = action.payload;
},
},
});
export const { setName, setAge } = userSlice.actions;
export default userSlice.reducer;
3.创建一个Redux store并将这些模块整合起来。创建一个名为store.js
的文件:
javascript
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
import userReducer from './userSlice';
const store = configureStore({
reducer: {
counter: counterReducer,
user: userReducer,
},
});
export default store;
4.在你的应用程序的入口处,将store与React应用程序进行连接。创建一个名为App.js
的文件:
javascript
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
import User from './User';
function App() {
return (
<Provider store={store}>
<div>
<Counter />
<User />
</div>
</Provider>
);
}
export default App;
在组件Counter.js中使用
javascript
import { useDispatch,useSelector } from 'react-redux';
import {increment} from '../store/reducer/counterSlice'
export default function Counter() {
const value= useSelector(state=>state.counter.value);
const dispatch = ();
const changeValue = ()=>{
dispatch(increment())
}
return (
<div>
{value}
<button onClick={changeValue}>修改value</button>
</div>
)
}