React-Redux 就是对redux的封装,它将所有组件分成两大类:UI 组件和容器组件
UI组件只负责 UI 的呈现,不带有任何业务逻辑
容器组件负责管理数据和业务逻辑
我先不使用react-redux实现一个计数器
import React, { Component } from 'react'
import store from '../../store'
import actionCreator from './actionCreator'
class One extends Component { //UI组件
render() {
let {n,compute} = this.props
return (
<div>
<button onClick={compute.bind(this,-1)}>-</button>
{n}
<button onClick={compute.bind(this,1)}>+</button>
</div>
);
}
}
class OneContainer extends Component { //容器组件
constructor(props){
super(props)
this.state = {
n:store.getState().n
}
store.subscribe(this.change.bind(this)) //监听store中数据的变化
}
change(){ //当store里数据修改的时候会执行这个回调函数
this.setState({
n:store.getState().n
})
}
compute(p){
store.dispatch(actionCreator.comAction(p)) //抛发动作给reducer,reducer中的action可以接收
}
render() {
return (
<div>
<One n={this.state.n} compute={this.compute}/>
</div>
)
}
}
export default OneContainer
如果使用react-redux,我们只需要写UI组件中的代码,容器组件则是由 React-Redux 自动生成
react-redux 的两个最主要功能:
Provider :提供包含 store的context;通过context可以将store传给下面的所有子孙组件
connect :连接数据处理组件和内部UI组件;
- 安装
npn install react-redux -S
- 在入口文件index.js中引入,Provider包裹App组件,并传入写好的store
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux' //引入Provider
import store from './store' //引入store
ReactDOM.render(
//用Provider包裹App组件,将store传出去
<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
- 在要使用的组件中引入connect,connect是一个高阶组件 连接容器组件和ui组件
import React, { Component } from 'react'
import actionCreator from './actionCreator'
import {connect} from 'react-redux' //引入connect 高阶组件 连接容器组件和ui组件
class One extends Component { //UI组件
render() {
console.log(this.props)
let {n,comAction} = this.props
return (
<div>
<button onClick={comAction.bind(this,-1)}>-</button>
{n}
<button onClick={comAction.bind(this,1)}>+</button>
</div>
);
}
}
export default connect((state)=>state,actionCreator)(One) //第一个参数是redux中的state,第二个参数是抛发的动作
这段代码和最上面的代码,实现的效果是同样的,使用react-redux只需要简单的三步,就能减少很多代码
逆战班