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

首頁 > 開發(fā) > JS > 正文

用react-redux實現(xiàn)react組件之間數(shù)據(jù)共享的方法

2024-05-06 16:44:51
字體:
供稿:網(wǎng)友

上篇文章寫到了redux實現(xiàn)組件數(shù)據(jù)共享的方法,但是在react中,redux作者提供了一個更優(yōu)雅簡便的模塊實現(xiàn)react組件之間數(shù)據(jù)共享。那就是利用react-redux

利用react-redux實現(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接收兩個函數(shù)作為參數(shù),一個mapStateToProps定義哪些store屬性會被映射到根組件上的屬性(把store傳入react組件),一個mapDispatchToProps定義哪些行為action可以作為根組件屬性(把數(shù)據(jù)從react組件傳入store)

3.定義這兩個映射函數(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是一個包含了action構(gòu)建函數(shù)的對象,用bindActionCreators把對象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>  ) }}

因為我們采用了bindActionCreators函數(shù),創(chuàng)建action后會立即自動調(diào)用store.dispatch(action)將數(shù)據(jù)更新到store.

這樣我們就利用react-redux模塊完成了react各個組件之間數(shù)據(jù)共享。

跟上篇文章一樣,實現(xiàn)了在一個組件Input中通過actions更新數(shù)據(jù)到store,然后在另一個組件Show中展示store中的數(shù)據(jù)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 洛隆县| 昭觉县| 黄石市| 大埔县| 济阳县| 长乐市| 保康县| 高清| 萍乡市| 合山市| 内黄县| 彝良县| 张家港市| 商城县| 台东市| 荥经县| 乌拉特后旗| 逊克县| 内黄县| 霍邱县| 手游| 驻马店市| 荥经县| 微山县| 沙田区| 新郑市| 松潘县| 即墨市| 伊宁县| 民丰县| 金华市| 徐州市| 益阳市| 西乡县| 阿坝县| 漠河县| 黄石市| 白玉县| 浦城县| 漳州市| 宜君县|