用Redux-Toolkit写一个简单的例子
时间: 2024-10-08 15:16:30 浏览: 31
redux-toolkit-saga:像@reduxjstoolkit一样的redux-saga样式
Redux Toolkit是Redux库的一套官方推荐工具集,它简化了Redux的创建、管理以及与其他状态管理库的集成过程。下面是一个简单的Redux Toolkit使用示例:
首先,你需要安装`@reduxjs/toolkit`,这是一个包含许多实用功能的库:
```bash
npm install @reduxjs/toolkit react-redux
```
然后,在store.js文件中,初始化Redux Store:
```javascript
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers'; // 这里假设你有一个名为rootReducer的合并所有reducer的函数
const store = configureStore({
reducer: rootReducer,
middleware: () => ([
// 可选:添加中间件,例如thunk或redux-saga
applyMiddleware(thunk),
]),
});
export default store;
```
接着,在reducers文件夹下创建action creators和reducers:
```javascript
// actions.js
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
// counterSlice.js
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: (state) => state + 1,
decrement: (state) => state - 1,
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
```
最后,在需要使用state的地方,通过`useSelector`和`useDispatch`获取数据和触发action:
```jsx
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from '../actions';
function Counter() {
const count = useSelector((state) => state.counter);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch(increment())}>+</button>
<p>{count}</p>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
}
export default Counter;
```
阅读全文