React Redux:如何将特定对象道具从商店传递到子组件?

React Redux: How to pass specific object prop from store to child component?

我的商店中有一组对象,还有一个页面列出了商店中的所有商品。我想要一个组件,仅列出其中一个项目的信息。但我不明白如何将单个项目的对象从商店传递到组件。

Router.js:

<Route path="/" component={MainLayout}>
    <IndexRoute component={EventListContainer} />
    <Route path=":eventID" component={EventProfileContainer} />
</Route>

因此,根页面没有问题,它列出了商店中的所有活动项目。我想使用 :eventID 路由来列出各个事件项目。

EventProfileContainer.js:

import _ from 'lodash';

const EventProfileContainer = React.createClass({
  render: function() {
    return (
      <EventProfile {...this.props.event} />
    );
  } 
});

const mapStateToProps = function(store, ownProps) {
  return {
    event: _.find(store, 'id', ownProps.params.eventID)
  };
};

export default connect(mapStateToProps)(EventProfileContainer);

我认为这里的重要部分是 mapStateToProps 函数。我想我应该使用这部分从商店中选择单个对象:event: _.find(store, 'id', ownProps.params.eventID)(使用 lodash _.find())。但也许我遗漏了什么?

EventProfile.js:

export default function(props) {
  return (
    <div className="event-profile">
      <img src={props.image} />
      <div className="details">
        <h1>{props.name}</h1>
        <p>{props.description}</p>
      </div>
    </div>
  );
}

正在向 EventProfile.js 传递一些内容,但页面显示为空白。名称、ID、图像和描述均为空白。商店中的对象如下所示:

name: 'name of the event',
id: '2342343'
description: 'description of the event'
image: 'http://whatever.com/whatever.jpg'

我不知道我做错了什么。感谢您的帮助!

看看 the signature of _.find — 它需要一个谓词,而不是属性名称和值。尝试这样的事情:

event: _.find(store, (e) => e.id == ownProps.eventID)

(顺便说一句,调用 mapStateToProps 函数的第一个参数 store 有点令人困惑,因为它不是传递给函数的存储,而是状态,即是,store.getState())

这是一个最小的 运行 示例:

var store = Redux.createStore(
  (state) => state, {
    events: [
      {name: "event name here", id: "12345", description: "wat"},
      {name: "another event", id: "42", description: "nope"},
    ],
  }
);

function EventProfile(props) {
  return (
    <p>{props.event.name} ({props.event.id})</p>
  );
}
EventProfile = ReactRedux.connect((state, ownProps) => {
  return {
    event: _.find(state.events, (e) => e.id == ownProps.eventID),
  }
})(EventProfile);

ReactDOM.render(
  <EventProfile eventID="42" store={store}/>,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.6.0/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/4.4.5/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
<div id="root"></div>