2016-03-07 77 views
19

我已经写了使用终极版和我实施mapDispathToProps容器组件看起来像这样访问国家内部的mapDispatchToProps方法

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

的问题是,为了getTableData我需要一些其他组件的状态。我怎样才能访问该方法中的状态对象?

回答

20

可以使用终极版-的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)) 
     } 
    } 
} 

一些不同的方式去组织这些事,但像这应该工作。

+0

我认为真正的使用情况下,用于访问mapDispatchToProps状态是知道哪些行为是在运行时可用。例如,您可以将每个可能的操作映射到函数,并调用它来分派操作或使用if子句对其进行测试,以检查操作是否可用。 –

2

你可以使用redux-thunk来获得状态。 写一个辅助函数是这样的:

const getState = (dispatch) => new Promise((resolve) => { 
    dispatch((dispatch, getState) => {resolve(getState())}) 
}) 

您可以在异步功能或发电机功能使用:

const mapDispatchToProps = (dispatch, ownProps) => { 
    return { 
    async someFunction() { 
     const state = await getState(dispatch) 
     ... 
    } 
    } 
} 
0

可能的方法是使用也mergeProps该合并mapStatemapDispatch并允许使用两者在同一时间。

// 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); 

正式文件:在大型应用程式react-redux#connect

可能的性能缺点:Stack Overflow - Performances and mergeProps in Redux