Appearance
react-redux使用
本节目标:理解“react-redux使用”的核心思路,并能把它用于实际开发或面试表达。
React-redux充分利用了react中的context; 提供了Provider和connect两个api; 安装Npm I react-redux -S
Provider.jsconnect.js
src\index.js
importReact from
'react';
importReactDOM from
'react-dom';
importCounter1 from
'./components/Counter1';
importCounter2 from
'./components/Counter2';
import{ Provider } from
'react-redux';
importstore from
'./store';
ReactDOM.render(<Providerstore={store}><Counter1/\>
<Counter2/\>
</Provider>,document.getElementById('root'));src\components\Counter1.js 使用了connect导入全局state和
actions:
importReact,{ Component } from
'react'
import{ connect } from
'react-redux';
importactions from
'../store/actions/counter1';
//Counter1.props=
{...state.counter1,...actions};
classCounter1 extends Component {
render(){let {
color,number,add1,minus1,changeColor } =
this.props; `return` `(`
<divstyle={{color
}}><p>{number}</p><buttononClick={add1}>+</button><buttononClick={minus1}>-</button><buttononClick={()=\>
changeColor('red')}>改成红色
</button></div> `)`
}
}
//把仓库中的状态映射为组件的属性 let mapStateToProps = state =\>
state.counter1;
//把派发的动作映射为属性对象 //let mapDispatchToProps,执行结果为
actions
exportdefault
connect(
//这里的State指redux中的全局state
mapStateToProps,actions
)(Counter1);/*** 组件关联仓库两个方向 * 输入 组件里使用仓库提供的状态进行组件的渲染 * 输出 在组件可以派发动作从而修改仓库中的状态 */
src\components\Counter2.js
importReact,{ Component } from
'react'
import{ connect } from
'react-redux';
importactions from
'../store/actions/counter2';
//Counter2.props=
{...state.counter2,...actions};
classCounter2 extends Component {
render(){let {
color,number,add2,minus2,changeColor } =
this.props; `return` `(`
<divstyle={{color
}}><p>{number}</p><buttononClick={add2}>+</button><buttononClick={minus2}>-</button><buttononClick={()=\>
changeColor('green')}>改成绿色
</button></div> `)`
}
}
//把仓库中的状态映射为组件的属性对象 输入 let mapStateToProps = state =\>
state.counter2;
//把派发的动作映射为属性对象 //let
mapDispatchToProps
exportdefault
connect(mapStateToProps,actions
)(Counter2);
/*** 组件关联仓库两个方向 * 输入 组件里使用仓库提供的状态进行组件的渲染 * 输出 在组件可以派发动作从而修改仓库中的状态 */
