React-redux mapStateToProps,mapDispatchToProps 如何使用

來源:互聯網
上載者:User

標籤:最佳實務   prope   參數   是你   options   rop   使用   render   javascrip   

 
使用 react-redux首先在最外層容器中,把所有內容包裹在 Provider 組件中,將之前建立的 store 作為 prop 傳給 Provider 。const App = () => {  return (    <Provider store={store}>      <Comp/>    </Provider>  )};Provider 內的任何一個組件(比如這裡的 Comp ),如果需要使用 state 中的資料,就必須是「被 connect 過的」組件——使用 connect 方法對「你編寫的組件( MyComp )」進行封裝後的產物。class MyComp extends Component {  // content...}const Comp = connect(...args)(MyComp);可見, connect 方法是重中之重。connect 詳解究竟 connect 方法到底做了什麼,我們來一探究竟。首先看下函數的簽名:connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])connect() 接收四個參數,它們分別是 mapStateToProps , mapDispatchToProps , mergeProps 和 options 。mapStateToProps(state, ownProps) : stateProps這個函數允許我們將 store 中的資料作為 props 綁定到組件上。const mapStateToProps = (state) => {  return {    count: state.count  }}這個函數的第一個參數就是 Redux 的 store ,我們從中摘取了 count 屬性。因為返回了具有 count 屬性的對象,所以 MyComp 會有名為 count 的 props 欄位。class MyComp extends Component {  render(){    return <div>計數:{this.props.count}次</div>  }}const Comp = connect(...args)(MyComp);當然,你不必將 state 中的資料原封不動地傳入組件,可以根據 state 中的資料,動態地輸出組件需要的(最小)屬性。const mapStateToProps = (state) => {  return {    greaterThanFive: state.count > 5  }}函數的第二個參數 ownProps ,是 MyComp 自己的 props 。有的時候, ownProps 也會對其產生影響。比如,當你在 store 中維護了一個使用者列表,而你的組件 MyComp 只關心一個使用者(通過 props 中的 userId 體現)。const mapStateToProps = (state, ownProps) => {  // state 是 {userList: [{id: 0, name: ‘王二‘}]}  return {    user: _.find(state.userList, {id: ownProps.userId})  }}class MyComp extends Component {    static PropTypes = {    userId: PropTypes.string.isRequired,    user: PropTypes.object  };    render(){    return <div>使用者名稱:{this.props.user.name}</div>  }}const Comp = connect(mapStateToProps)(MyComp);當 state 變化,或者 ownProps 變化的時候, mapStateToProps 都會被調用,計算出一個新的 stateProps ,(在與 ownProps merge 後)更新給 MyComp 。這就是將 Redux store 中的資料連線到組件的基本方式。mapDispatchToProps(dispatch, ownProps): dispatchPropsconnect 的第二個參數是 mapDispatchToProps ,它的功能是,將 action 作為 props 綁定到 MyComp 上。const mapDispatchToProps = (dispatch, ownProps) => {  return {    increase: (...args) => dispatch(actions.increase(...args)),    decrease: (...args) => dispatch(actions.decrease(...args))  }}class MyComp extends Component {  render(){    const {count, increase, decrease} = this.props;    return (<div>      <div>計數:{this.props.count}次</div>      <button onClick={increase}>增加</button>      <button onClick={decrease}>減少</button>    </div>)  }}const Comp = connect(mapStateToProps, mapDispatchToProps)(MyComp);由於 mapDispatchToProps 方法返回了具有 increase 屬性和 decrease 屬性的對象,這兩個屬性也會成為 MyComp 的 props 。如上所示,調用 actions.increase() 只能得到一個 action 對象 {type:‘INCREASE‘} ,要觸發這個 action 必須在 store 上調用 dispatch 方法。 diapatch 正是 mapDispatchToProps 的第一個參數。但是,為了不讓 MyComp 組件感知到 dispatch 的存在,我們需要將 increase 和 decrease 兩個函數封裝一下,使之成為直接可被調用的函數(即,調用該方法就會觸發 dispatch )。Redux 本身提供了 bindActionCreators 函數,來將 action 封裝成直接可被調用的函數。import {bindActionCreators} from ‘redux‘;const mapDispatchToProps = (dispatch, ownProps) => {  return bindActionCreators({    increase: action.increase,    decrease: action.decrease  });}同樣,當 ownProps 變化的時候,該函數也會被調用,產生一個新的 dispatchProps ,(在與 statePrope 和 ownProps merge 後)更新給 MyComp 。注意, action 的變化不會引起上述過程,預設 action 在組件的生命週期中是固定的。[mergeProps(stateProps, dispatchProps, ownProps): props]之前說過,不管是 stateProps 還是 dispatchProps ,都需要和 ownProps merge 之後才會被賦給 MyComp 。 connect 的第三個參數就是用來做這件事。通常情況下,你可以不傳這個參數, connect 就會使用 Object.assign 替代該方法。其他最後還有一個 options 選項,比較簡單,基本上也不大會用到(尤其是你遵循了其他的一些 React 的「最佳實務」的時候),本文就略過了。希望瞭解的同學可以直接看文檔。

  

轉載自:https://www.tuicool.com/articles/MrmYN36

React-redux mapStateToProps,mapDispatchToProps 如何使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.