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

2019-11-16,,,,,

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

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

1.安装react-redux

$ npm i --save react-redux

2.从react-redux导入Prodiver组件将store赋予Provider的store属性,

将根组件用Provider包裹起来。

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

这样根组件中所有的子组件都可以获得store中的值

3.connect二次封装根组件

export default connect(mapStateToProps,mapDispatchToProps)(Wrap)

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

3.定义这两个映射函数

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中的数据

<Input actions={this.props.actions} ></Input>

先将actions作为属性传入子组件

子组件调用actions中的方法创建action

//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中的数据

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • Android数据共享 sharedPreferences 的使用方法
  • 使用Runnable实现数据共享

《用react-redux实现react组件之间数据共享的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。