用react-redux实现react组件之间数据共享

上篇文章写到了redux实现组件数据共享的方法,可是在react中,redux做者提供了一个更优雅简便的模块实现react组件之间数据共享。那就是利用react-reduxreact


利用react-redux实现react组件数据之间数据共享

1.安装react-redux
$ npm i --save react-redux
2.从react-redux导入Prodiver组件将store赋予Provider的store属性,
将根组件用Provider包裹起来。npm

import {Provider,connect} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
  <Wrap/>
</Provider>,document.getElementById('example'))

这样根组件中全部的子组件均可以得到store中的值
3.connect二次封装根组件redux

export default connect(mapStateToProps,mapDispatchToProps)(Wrap)

connect接收两个函数做为参数,一个mapStateToProps定义哪些store属性会被映射到根组件上的属性(把store传入react组件),一个mapDispatchToProps定义哪些行为action能够做为根组件属性(把数据从react组件传入store)
3.定义这两个映射函数ide

function mapStateToProps(state){
  return {
    name:state.name,
    pass:state.pass
  }
}
function mapDispatchToProps(dispatch){
 
  return {actions:bindActionCreators(actions,dispatch)
  }
}

把store中的name,pass映射到根组件的name,pass属性。
actions是一个包含了action构建函数的对象,用bindActionCreators把对象actions绑定到根组件actions属性上。
4.在根组件引用子组件的位置用 <Show name={this.props.name} pass={this.props.pass}></Show>将store数据传入子组件.函数

5.在子组件中调用actions中的方法来更新store中的数据this

<Input actions={this.props.actions} ></Input>
  • 先将actions做为属性传入子组件spa

  • 子组件调用actions中的方法建立actioncode

//Input组件
export default class Input extends React.Component{
sure(){
this.props.actions.add({name:this.refs.name.value,pass:this.refs.pass.value})
}
  render(){ 
    return (
        <div>  
   姓名:<input ref="name" type="text"/>
   密码:<input  ref="pass" type="text"/>
   <button onClick={this.sure.bind(this)}>登陆</button>
  </div>

    )
  }
}
  • 由于咱们采用了bindActionCreators函数,建立action后会当即自动调用store.dispatch(action)将数据更新到store.对象


这样咱们就利用react-redux模块完成了react各个组件之间数据共享。
跟上篇文章同样,实现了在一个组件Input中经过actions更新数据到store,而后在另外一个组件Show中展现store中的数据get

相关文章
相关标签/搜索