Access State inside of mapDispatchToProps method

前端 未结 5 1848
清歌不尽
清歌不尽 2021-01-30 16:37

I have written a container component using redux and my implementation for mapDispatchToProps looks like this

const mapDispatchToProps = (dispatch, o         


        
5条回答
  •  星月不相逢
    2021-01-30 16:49

    Possible approach is also to use mergeProps that merges mapState and mapDispatch and allows to use both at the same time.

    // Define mapState
    const mapState = (state) => ({
      needeedValue: state.neededValue
    })
    
    // Define mapDispatch
    const mapDispatch = (dispatch, ownProps) => {
      return {
        onChange: (newValue, neededValue) => {
          dispatch(updateAttributeSelection('genre', newValue));
          dispatch(getTableData(newValue, ownProps.currentYear, neededValue));
        }
      }
    }
    
    // Merge it all (create final props to be passed)
    const mergeProps = (stateProps, dispatchProps, ownProps) => {
      return {
        ...stateProps,  // optional
        ...dispatchProps,  // optional
        onChangeWithNeededValue: (newValue) => (
          dispatchProps.onChange(
            newValue,
            stateProps.needeedValue  // <<< here the magic happens
          )
        )
      }
    }
    
    // Pass mergePros to connect
    const MyContainer = connect(mapState, mapDispatch, mergeProps)(MyComponent);
    

    Official documentation: react-redux#connect

    Possible performance drawback on larger apps: Stack Overflow - Performances and mergeProps in Redux

提交回复
热议问题