如果之前有人问过这个问题,我很抱歉...我进行了搜索,但找不到解决方案。无论如何...
我已成功从我的 API 映射出数据。
在我的 HomePage.js
组件中,我有以下内容:
componentWillMount() {
this.props.dispatch(fetchOrdersAction());
}
...
{orders.data.length > 0 &&
<div className="order-items d-flex flex-row align-items-stretch flex-wrap">
{orders.data.map((list, index) =>
<ListOrderItem order={list} key={index} clickHandler={this.handleListCardClick} />
)}
</div>
}
在我的 ListOrderItem.js
中,我的渲染看起来像这样:
render() {
const { order, user} = this.props;
return (
<div className="order-item d-flex justify-content-between" onClick={this.handleClick}>
<span className="name-data-holder">{order.user_id}</span>
<span className="date-data-holder"><Moment date={order.created_at} format="MM/DD/YYYY"/></span>
<span className="product-name-data-holder">id: {order.product_id}</span>
<span className="price-data-holder">${order.amount}</span>
<span className="actions-data-holder">
<p className="sm-red-action-btn">View Order</p>
</span>
</div>
);
}
目前,我正在返回按预期工作的 {order.user_id}
。我现在想做的是获取与该 ID 关联的用户的名字。
我的想法是创建一个如下的调度:
this.props.dispatch(fetchUsersAction(`filter[id]=5`));
我将其添加到 HomePage.js
如果我查看网络选项卡,我可以看到调度成功并且正在返回用户 5 的数据。
我正在努力解决以下问题:
- 让它在
listOrderItem
的每个实例中运行 - 将用户 ID 动态传递给过滤器
我尝试在 ListOrderItem
内运行调度,但收到类似于 functions not valid as a React child
如果能朝着正确的方向插入,我们将不胜感激!非常感谢。
最佳答案
也许您可以在 componentWillMount() 函数中从 ListOrderItem.js 进行调度
componentWillMount() {
const {order} = this.props
this.props.dispatch(fetchUsersAction(`filter[id]=${order.user_id}`));
}
但这听起来像是列表中的大量 api 调用。 您可以直接从 api 将它们插入到响应中吗?
关于javascript - 使用react,从子组件内的ID获取用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480080/