2016-03-07 83 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