由于react日常开发人们习惯使用redux做状态管理
FaceBook官方就出了一个react-redux插件,专门用于react的状态管理
更简单,更方便,更舒适
connect(mapStateToProps,mapDispatchToProps)(UI组件)
安装指令:
yarn add react-redux
或npm i react-redux
此处修改的是 三、【redux】异步action 的求和Demo
创建containers文件夹放置容器组件
安装指令:
yarn add react-redux
或npm i react-redux
/**
* 这是Count的容器组件
*/
// 引入 Count 的UI组件
import CountUI from '../../components/Count_Redux'
// 引入 connect 用于连接UI组件与Redux
import { connect } from 'react-redux'
//引入action
import {
createIncrementAction,
createDecrementAction,
createIncrementAsyncAction
} from '../../redux/count_action'
/*
1.mapStateToProps函数返回的是一个对象;
2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
3.mapStateToProps用于传递状态
*/
function mapStateToProps(state) {
return { count: state }
}
/*
1.mapDispatchToProps函数返回的是一个对象;
2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch) {
return {
add: num => dispatch(createIncrementAction(num)),
sub: num => dispatch(createDecrementAction(num)),
asyncAdd: (num, time) => dispatch(createIncrementAsyncAction(num, time)),
}
}
// connect创建并返回一个Count的容器组件
export default connect(mapStateToProps, mapDispatchToProps)(CountUI)
- 导入的Count改为容器组件
- 手动将store通过props形式传给Count容器组件
import React, { Component } from 'react'
import Count from './containers/Count' // 改为容器组件
import store from './redux/store'
export default class App extends Component {
render() {
return (
<div>
<Count store={store} />
</div>
);
}
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from './redux/store'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
//监测redux中状态的改变,如redux的状态发生了改变,那么重新渲染App组件
store.subscribe(() => {
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
})
import React, { Component } from 'react'
export default class Count extends Component {
state = {
num: 1
}
add = () => {
const { num } = this.state
this.props.add(num)
}
sub = () => {
const { num } = this.state
this.props.sub(num)
}
oddAdd = () => {
const { num } = this.state
const { count } = this.props
if (count % 2 === 1) {
this.props.add(num)
}
}
asyncAdd = () => {
const { num } = this.state
this.props.asyncAdd(num, 2000)
}
render() {
const { count } = this.props
return (
<div>
<h1>当前求和为:{count}</h1>
{/*其他未变...略...*/}
</div >
)
}
}