1、react-redux
是一个插件库
2、连接容器组件和redux组件
安装react-redux库
npm i react-redux --save
1、创建容器文件夹container,并创建响应的容器组件count,及index.js
2、container/count/index.js
//引入count的ui组件
import CountUI from '../../component/Count'
import {
createIncreatmentAciton,
createDecreatmentAciton,
createDecreatmentAsyncAciton
} from '../../redux/count_action'
//引入connect用于连接ui组件与redux
import {connect} from 'react-redux'
//mapStateToProps函数返回的对象中的key就作为传递给ui组件props的key,value就作为传递给ui组件props的value-状态
function mapStateToProps (state) {
return {count:state}
}
//mapDispatchToProps函数返回的对象中的key就作为传递给ui组件props的key,value就作为传递给ui组件props的value-操作状态
function mapDispatchToProps (dispatch) {
return {
jia:(number)=>{
//通知redux执行加法
dispatch(createIncreatmentAciton(number))
},
jian:(number)=>{
//通知redux执行加法
dispatch(createDecreatmentAciton(number))
},
jiaAsync:(number,time)=>{
//通知redux执行加法
dispatch(createDecreatmentAsyncAciton(number,time))
}
}
}
//获得一个容器组件
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)
3、component/count/index.js
import React, { Component } from 'react'
// //引入store中保存的状态
// import store from '../../redux/store'
// //引入actionCreator,专门用于创建action对象
// import {
// createDecreatmentAciton,
// createIncreatmentAciton,
// createDecreatmentAsyncAciton
// } from '../../redux/count_action'
class Count extends Component {
//加法
increament=()=>{
//函数体
const {value}=this.selectNumber
this.props.jia(value*1)
}
//减法
decreament=()=>{
//函数体
const {value}=this.selectNumber
this.props.jian(value*1)
}
//奇数在加
increamentIfOdd=()=>{
//函数体
const {value}=this.selectNumber
if (this.props.count % 2 ===1){
this.props.jian(value*1)
}
}
increamentAsync=()=>{
//函数体
const {value}=this.selectNumber
this.props.jiaAsync(value*1,500)
}
render () {
console.log(this.props)
return (
<div>
<h1>当前求和为:{this.props.count}</h1>
<select ref={currentNode=>this.selectNumber=currentNode}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={this.increament}>+</button>
<button onClick={this.decreament}>-</button>
<button onClick={this.increamentIfOdd}>当前求和我技术再加</button>
<button onClick={this.increamentAsync}>异步+</button>
</div>
)
}
}
export default Count
4、app.js
import React, { Component } from 'react'
import Count from './container/Count'
import store from './redux/store'
export default class App extends Component {
render () {
return (
<div>
{/*给容器组件传递store*/}
<Count store={store}/>
</div>
)
}
}
3、provider组件的使用
提供渲染,不需要单独再强制渲染app组件
项目下index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './redux/store'
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
4、整合ui组件和容器组件
5、redux开发者工具
还需要安装redux-devtools-extension
npm install --save-dev redux-devtools-extension
在sotre.js中引入
import {composWithDevTools} from 'redux-devtools-extension'
后面还有一些繁琐的内容