用react-redux實現react元件之間資料共享

Ajaxyz發表於2017-05-13

上篇文章寫到了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中的資料

相關文章