react redux写法
时间: 2024-09-21 14:03:00 浏览: 37
react-Redux繁琐模板写法解决方案
React Redux是一个结合了React和Redux的库,用于管理单页应用的状态。它的核心思想是将应用程序的状态集中存储在一个单一的store中,并通过reducer函数来更新这个状态。下面是React Redux的基本写法:
1. **安装依赖**:首先需要安装`react-redux`、`redux`和`@reduxjs/toolkit`等库。
```bash
npm install react-redux redux react-redux Toolkit
```
2. **创建store**:在应用入口处创建Redux store,通常在`index.js`或`store.js`文件中。
```javascript
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';
const store = configureStore({
reducer: rootReducer,
});
```
3. **创建reducer**:对每个应用状态进行分片管理,编写一个个reducer函数处理action。
```javascript
// rootReducer.js
import counterReducer from './counterReducer';
export default combineReducers({
counter: counterReducer,
});
```
4. **动作(Action)**:代表状态变化的行为,通常包含一个type属性和可选的数据。
```javascript
// actions.js
export const increment = () => ({
type: 'INCREMENT',
});
export const decrement = () => ({
type: 'DECREMENT',
});
```
5. **组件连接(Provider and Connect)**:在根组件上挂载store,然后在其他组件上使用`connect`高阶组件来获取并订阅state。
```javascript
// App.js
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
export default App;
```
6. **智能组件(Container)**:使用`mapStateToProps`和`mapDispatchToProps`从store提取数据到props,并处理actions。
```javascript
// Counter.js
import { connect } from 'react-redux';
import { increment, decrement } from './actions';
function Counter({ count, dispatch }) {
function handleClick(type) {
dispatch(type());
}
return (
<div>
<button onClick={() => handleClick(increment)}>+</button>
<span>{count}</span>
<button onClick={() => handleClick(decrement)}>-</button>
</div>
);
}
const mapStateToProps = (state) => ({ count: state.counter });
const mapDispatchToProps = { increment, decrement };
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
```
阅读全文