React 不会呈现 children,但控制台日志正确
React won't render children, but console logs correctly
我正在尝试将块列表呈现为我的页面组件的 children。到目前为止,我只看到 console.log 个方块出现。这些块根本不呈现,即使控制台中的数据正常。
我做错了什么
var Block = React.createClass({
render: function() {
var block = this.props.item;
return (
<div className="row" key={block.id}>
<p>{block.name}</p>
</div>
);
}
});
var Page = React.createClass({
getInitialState: function() {
return {
page: '',
blocks: [],
newBlockValue: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get("/pages/"+this.props.page+".json", function (result) {
this.setState({
page: result.page,
blocks: result.blocks
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
var page = this.state.page;
return (
<div className="row">
{this.state.blocks.forEach(function(block){
console.log(block);
<Block key={block.id} item={block} />
})}
<form id="add_new_block">
<input type="text" id="new_block" value={this.state.newBlockValue} onChange={this.handleChange} autoComplete="off"/>
<input type="submit" value='Save' onClick={this.createBlock}/>
</form>
</div>
);
}
您应该使用 map
而不是 forEach
。
正在数组 returns undefined
上调用 forEach
。你想给你的 Page
元素一个 Block
元素的数组,而不是 undefined
.
你还应该 return
你的 Block
元素,否则你最终会得到一个 undefined
:
的数组
this.state.blocks.map(function(block){
return <Block key={block.id} item={block} />
})
我正在尝试将块列表呈现为我的页面组件的 children。到目前为止,我只看到 console.log 个方块出现。这些块根本不呈现,即使控制台中的数据正常。
我做错了什么
var Block = React.createClass({
render: function() {
var block = this.props.item;
return (
<div className="row" key={block.id}>
<p>{block.name}</p>
</div>
);
}
});
var Page = React.createClass({
getInitialState: function() {
return {
page: '',
blocks: [],
newBlockValue: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get("/pages/"+this.props.page+".json", function (result) {
this.setState({
page: result.page,
blocks: result.blocks
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
var page = this.state.page;
return (
<div className="row">
{this.state.blocks.forEach(function(block){
console.log(block);
<Block key={block.id} item={block} />
})}
<form id="add_new_block">
<input type="text" id="new_block" value={this.state.newBlockValue} onChange={this.handleChange} autoComplete="off"/>
<input type="submit" value='Save' onClick={this.createBlock}/>
</form>
</div>
);
}
您应该使用 map
而不是 forEach
。
正在数组 returns undefined
上调用 forEach
。你想给你的 Page
元素一个 Block
元素的数组,而不是 undefined
.
你还应该 return
你的 Block
元素,否则你最终会得到一个 undefined
:
this.state.blocks.map(function(block){
return <Block key={block.id} item={block} />
})