react安装redux reduxjs/toolkit
时间: 2024-09-24 20:12:50 浏览: 44
React 安装 Redux 和 Redux Toolkit 的步骤如下:
1. **安装Redux**: 首先需要安装Redux库。你可以使用npm或yarn来添加依赖。通过终端或命令行运行以下命令:
```bash
npm install redux
# 或者如果使用Yarn
yarn add redux
```
2. **安装Redux Toolkit (RTK)**: Redux Toolkit是一个官方推荐的库,它简化了Redux的工作流,包括创建store、action creators、reducers等。安装时同样使用npm或yarn:
```bash
npm install @reduxjs/toolkit
# 或者Yarn
yarn add @reduxjs/toolkit
```
安装完成后,你可以在React项目中创建Redux store,并配置基本的reducer和actions。例如,在`src/reducers/index.js`中:
```javascript
import { createSlice } from '@reduxjs/toolkit';
// 创建一个简单的slice
const counterSlice = createSlice({
name: 'counter',
initialState: { count: 0 },
reducers: {
increment: (state) => ({ count: state.count + 1 }),
decrement: (state) => ({ count: state.count - 1 }),
},
});
export default counterSlice.reducer;
```
然后在`src/store.js`里创建并结合应用这个store:
```javascript
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './reducers';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export default store;
```
最后,在你需要的地方可以使用`useSelector`和` useDispatch` hooks从store中获取数据和触发actions:
```jsx
import React from 'react';
import { useSelector, useDispatch } from '@reduxjs/toolkit';
function Counter() {
const count = useSelector((state) => state.counter.count);
const dispatch = useDispatch();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(counterSlice.actions.increment())}>+</button>
<button onClick={() => dispatch(counterSlice.actions.decrement())}>-</button>
</div>
);
}
export default Counter;
```
阅读全文