【问题标题】:pass props to selectors to filter based on that props将道具传递给选择器以根据该道具进行过滤
【发布时间】:2017-07-04 03:13:33
【问题描述】:

我需要将道具传递给选择器,以便我可以从选择器中获取单击项目的内容。但是我无法通过道具。我试过这种方法但没有成功

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

【问题讨论】:

  • 请添加更多代码..
  • 用完整代码更新了我的问题@SantoshRamKunjir

标签: javascript reactjs redux reselect


【解决方案1】:

只需将状态和道具从您的mapStateToProps 传递给您的选择器。

如果您直接使用选择器作为 mapStateToProps 函数,它将接收与 mapState 相同的参数:state 和 ownProps(在连接组件上设置的属性)。

一个简单的例子:

// 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' />

但是,您正在做一些奇怪的事情,例如映射选择器以供以后重用。它不能那样工作,至少它不打算那样使用。

您使用选择器来检索您的状态切片并将其作为道具传递给您的connected 组件。每当状态更改时,您的选择器将重新运行(由于重新选择而进行了一些缓存)。如果组件实际上从 Redux 检索的内容确实发生了变化,它将重新渲染。

所以你的FeatureEditDialog 组件也应该被连接,并且应该能够从 Redux 状态检索它需要的任何东西,只需在它自己的connect 调用中使用道具(哪个功能,哪个 id 等等) .

this.props.showDialog(dialog); 也是一个很大的代码气味。 ;)

【讨论】:

  • 感谢分享知识。我正在尝试学习所有很棒的软件包,例如 reselect、immutable、saga。我现在有了选择器的概念。如果你有时间,你能看看这个吗? stackoverflow.com/questions/44895561/…
  • 如果答案有效,您应该将其标记为已回答。
猜你喜欢
  • 2017-10-03
  • 2018-11-04
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多