【问题标题】:What is the idiomatic ReactJS way to deal with ?initial? state?处理 ?initial 的惯用 ReactJS 方式是什么?状态?
【发布时间】:2014-12-18 17:25:20
【问题描述】:

作为练习,我正在将a very, very simple video game 从 jQuery(重新)实现转换为我想要的惯用 ReactJS。我正在(试图)使用the React tutorial 作为我的参考。

jQuery 重新实现将状态存储为字符数组的数组。我目前正在尝试获取要在 ReactJS 中呈现的初始状态。最初我将 getInitialState() 设置为返回最初返回的数据(数组数组)。这不起作用,因为 ReactJS 似乎想要一个对象而不是数组 (React.js: arrays and "Critical assumptions about the merge functions have been violated" error)。

本教程在“教程 10”部分中使用了 Array.map(),这表明某种级别的包含数组可能会有所帮助:

现在数据在 CommentList 中可用,让我们动态渲染 cmets:

// tutorial10.js
var CommentList = React.createClass({
  render: function() {
    var commentNodes = this.props.data.map(function (comment) {
      return (
        <Comment author={comment.author}>
          {comment.text}
        </Comment>
      );
    });
    return (
      <div className="commentList">
        {commentNodes}
      </div>
    );
  }
});

转换字符网格(目前实现为数组数组)的最佳方法是什么?我是否将数组作为节点放在 this.state 上(状态可能会发生变化,所以我设置的是状态而不是道具),然后是 Array.map() (或二维的)?

【问题讨论】:

  • 你能分享一些你正在使用的数据样本吗?

标签: javascript arrays reactjs


【解决方案1】:

处理 ?initial 的惯用 ReactJS 方式是什么?状态?

理想情况下,默认数据作为 prop(s) 传递给根组件。例如

React.render(
  <MyApp gid={grid} />,
  container
);

但是,只需从 getInitialState 方法返回它也可以。

最初我将 getInitialState() 设置为返回最初返回的数据(数组的数组)。这没有用,因为 ReactJS 似乎想要一个对象而不是数组

让你的数据成为状态的一个方面:

getInitialState() {
  return {
    grid:  this.props.grid
  };
}

【讨论】:

    【解决方案2】:

    如果你使用的是 ES2015 synax,你可以直接在构造函数中初始化状态:

    constructor() {
      super();
      this.state = {...}
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2015-08-27
      • 1970-01-01
      • 2013-06-15
      • 2022-11-30
      相关资源
      最近更新 更多