国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

用react-redux實現react組件之間數據共享的方法

2024-05-06 15:33:32
字體:
來源:轉載
供稿:網友

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宿州市| 高邮市| 临西县| 东安县| 佳木斯市| 阜新市| 宾阳县| 沙河市| 山西省| 攀枝花市| 江阴市| 九寨沟县| 新化县| 尉氏县| 莆田市| 屏山县| 建始县| 岳阳市| 辽宁省| 米林县| 镇坪县| 临邑县| 同德县| 石林| 雷波县| 恩施市| 马山县| 浪卡子县| 长泰县| 泰兴市| 长岭县| 宁国市| 法库县| 三原县| 尼木县| 嘉善县| 治县。| 宁明县| 卓尼县| 木兰县| 政和县|