2017-07-04 75 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