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

4

1 回答 1

1

只需将 state 和 props 从您的选择器传递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' />

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

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

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

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

于 2017-07-04T10:39:25.497 回答