访问mapDispatchToProps方法中的State

Kno*_*uch 41 redux react-redux

我使用redux编写了一个容器组件,我对mapDispathToProps的实现看起来像这样

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onChange: (newValue) => {
            dispatch(updateAttributeSelection('genre', newValue));
            dispatch(getTableData(newValue, ownProps.currentYear));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,为了获取getTableData,我需要一些其他组件的状态.如何在此方法中访问状态对象?

mar*_*son 37

您可以使用redux-thunk创建一个单独的动作创建者函数,该函数可以访问getState,而不是在里面定义函数mapDispatchToProps:

function doTableActions(newValue, currentYear) {
    return (dispatch, getState) => {
        dispatch(updateAttributeSelection('genre', newValue));
        let state = getState();
        // do some logic based on state, and then:
        dispatch(getTableData(newValue, currentYear));
    }
}


let mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onChange : (newValue) => {
            dispatch(doTableActions(newValue, ownProps.currentYear))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一些不同的方式来组织这些,但这样的事情应该工作.

  • 从我的角度来看,做如此简单的事情却如此复杂。 (2认同)

exm*_*axx 14

可能的方法也是使用mergeProps合并mapState,mapDispatch并允许同时使用它们.

// 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);
Run Code Online (Sandbox Code Playgroud)

官方文档:react-redux #connect

较大的应用程序可能存在性能缺陷:Stack Overflow - Redux中的性能和mergeProps


小智 5

您可以使用redux-thunk来获取状态。编写这样的辅助函数:

const getState = (dispatch) => new Promise((resolve) => {
  dispatch((dispatch, getState) => {resolve(getState())})
})
Run Code Online (Sandbox Code Playgroud)

您可以在异步函数或生成器函数中使用此函数:

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    async someFunction() {
      const state = await getState(dispatch)
      ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)