2017-07-04 47 views
1

我需要將道具傳遞給選擇器,以便我可以從選擇器中獲取點擊項目的內容。然而我無法通過道具。我想這樣,但沒有成功將道具傳遞給選擇器以基於該道具進行過濾

const mapStateToProps = createStructuredSelector({ 
    features: selectFeatures(), 
    getFeatureToEditById: selectFeatureToEditById(), 
}); 

handleFeatureEdit = (event, feature) => { 
    event.preventDefault(); 
    console.log("feature handle", feature); 
    const dialog = (
    <FeatureEditDialog 
     feature={feature} 
     featureToEdit={selectFeatureToEditById(feature)} 
     onClose={() => this.props.hideDialog(null)} 
    /> 
); 
    this.props.showDialog(dialog); 
}; 

selectors.js 

const selectFeatureState = state => state.get("featureReducer"); 

const selectFeatureById = (_, props) => { 
    console.log("props", _, props); #if i get the id of feature here 
    # i could then filter based on that id from below selector and show 
    # the result in FeatureEditDialog component 
}; 

const selectFeatureToEditById =() => 
    createSelector(
    selectFeatureState, 
    selectFeatureById, 
    (features, featureId) => { 
     console.log("features", features, featureId); 
    } 
); 

下面是完整的代碼要點

https://gist.github.com/MilanRgm/80fe18e3f25993a27dfd0bbd0ede3c20

+0

請增加更多代碼.. –

+0

已更新我的問題的完整密碼@SantoshRamKunjir – Serenity

回答

1

只要從mapStateToProps同時通過狀態和道具到你的選擇。

如果直接使用選擇器作爲mapStateToProps函數,它將接收mapState執行的相同參數:stateownProps(在連接組件上設置的道具)。

一個簡單的例子:

// simple selector 
export const getSomethingFromState = (state, { id }) => state.stuff[id] 
// reselect selector 
export const getStuff = createSelector(
    getSomethingFromState, 
    (stuff) => stuff 
) 

// use it as mapDispatchToProps 
const mapDispatchToProps = getSomethingFromState 

const MyContainer = connect(mapDispatchToProps)(MyComponent) 

// and set id as an own prop in the container when rendering 
<MyContainer id='foo' /> 

然而,你正在做一些奇怪的事情,比如選擇映射到的時候重新使用。它不會那樣工作,至少它不打算以這種方式使用。

您可以使用選擇器來檢索您的狀態片並將其作爲道具傳遞給您的connect ed組件。每當狀態發生變化時,您的選擇器將重新運行(由於重新選擇了一些緩存)。如果組件實際上從Redux檢索到的內容確實發生了變化,它將重新渲染。

所以你FeatureEditDialog組件時,應連接爲好,應該能夠檢索任何它從終極版國家需要,只是在自己的connect呼叫使用道具(該功能,它的ID,等等)的。

this.props.showDialog(dialog);也是一個很大的代碼味道。 ;)

+0

感謝分享知識。我正在努力學習所有偉大的軟件包,如重新選擇,不可變,傳奇。我現在得到了選擇器的概念。如果你有時間,你能看看這個嗎? https://stackoverflow.com/questions/44895561/re-rendering-issues-when-using-hoc-for-loader – Serenity

+0

如果答案是有效的,你應該將其標記爲已回答。 – CharlieBrown