use*_*745 1 javascript reactjs
我有一些问题,React没有显示与组件的道具相关的数据:
import React from 'react';
import {ItemListing} from './ItemListing.js';
export var SearchResults = React.createClass({
render: function() {
console.log('Render called! SearchResults props', this.props); // Fires and displays data as expected
return (
<div>
{this.props.items.forEach(function(item) {
console.log(item); // Fires correctly
<ItemListing item={item} /> // Does not run - a console.log() inside the render method of this component does not fire
})}
</div>
)
}
});
Run Code Online (Sandbox Code Playgroud)
此组件在其父级内部加载<SearchResults items={this.state.items} />,并且console.log()上面的render函数内部确实显示了按预期加载的props(在最初加载为空之后,因为数据来自进一步上游的Ajax调用).
但是,forEach循环中的组件似乎没有加载,没有显示,并且它的render方法顶部的console.log()似乎没有激活.
我很反应,所以可能会遗漏一些明显的东西,但是有谁能告诉我我做错了什么?
而不是使用forEach你需要使用map.
该forEach方法被设计为具有副作用,因此不返回值(或者更确切地说它返回undefined).在forEach评估之后查看JSX文字.
return (
<div>
{undefined}
</div>
)
Run Code Online (Sandbox Code Playgroud)
相反,使用map并返回子组件.
return (
<div>
{this.props.items.map(function(item) {
console.log(item); // Fires correctly
return <ItemListing item={item} />;
})}
</div>
)
Run Code Online (Sandbox Code Playgroud)
评估之后,JSX文字看起来像这样(取决于多少项this.props.items):
return (
<div>
{[
<ItemListing item={this.props.items[0]} />,
<ItemListing item={this.props.items[1]} />,
// ...
<ItemListing item={this.props.items[n]} />,
]}
</div>
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
362 次 |
| 最近记录: |