React不会呈现子项,但控制台日志正确

时间:2016-04-12 17:40:30

标签: reactjs state react-router

我正在尝试将块列表呈现为我的Page组件的子项。到目前为止,我只看到出现了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>
    );
}

1 个答案:

答案 0 :(得分:4)

您应该使用map代替forEach

在数组上调用forEach会返回undefined。您希望为Page元素添加一个Block元素数组,而不是undefined

另外,您应该return Block元素,否则最终会得到一个undefined数组:

this.state.blocks.map(function(block){
    return <Block key={block.id} item={block} />
})