您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“react-redux怎么實(shí)現(xiàn)react組件之間數(shù)據(jù)共享的方法”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“react-redux怎么實(shí)現(xiàn)react組件之間數(shù)據(jù)共享的方法”這篇文章吧。
利用react-redux實(shí)現(xiàn)react組件數(shù)據(jù)之間數(shù)據(jù)共享
1.安裝react-redux
$ npm i --save react-redux
2.從react-redux導(dǎo)入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接收兩個(gè)函數(shù)作為參數(shù),一個(gè)mapStateToProps定義哪些store屬性會(huì)被映射到根組件上的屬性(把store傳入react組件),一個(gè)mapDispatchToProps定義哪些行為action可以作為根組件屬性(把數(shù)據(jù)從react組件傳入store)
3.定義這兩個(gè)映射函數(shù)
function mapStateToProps(state){ return { name:state.name, pass:state.pass } } function mapDispatchToProps(dispatch){ return {actions:bindActionCreators(actions,dispatch) } }
把store中的name,pass映射到根組件的name,pass屬性。
actions是一個(gè)包含了action構(gòu)建函數(shù)的對(duì)象,用bindActionCreators把對(duì)象actions綁定到根組件actions屬性上。
4.在根組件引用子組件的位置用 <Show name={this.props.name} pass={this.props.pass}></Show>
將store數(shù)據(jù)傳入子組件.
5.在子組件中調(diào)用actions中的方法來更新store中的數(shù)據(jù)
<Input actions={this.props.actions} ></Input>
先將actions作為屬性傳入子組件
子組件調(diào)用actions中的方法創(chuàng)建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> ) } }
因?yàn)槲覀儾捎昧薭indActionCreators函數(shù),創(chuàng)建action后會(huì)立即自動(dòng)調(diào)用store.dispatch(action)將數(shù)據(jù)更新到store.
這樣我們就利用react-redux模塊完成了react各個(gè)組件之間數(shù)據(jù)共享。
以上是“react-redux怎么實(shí)現(xiàn)react組件之間數(shù)據(jù)共享的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。