gpt4 book ai didi

javascript - ReactJS 处理“initial”的惯用方法是什么?状态?

转载 作者:行者123 更新时间:2023-12-03 11:11:45 26 4
gpt4 key购买 nike

作为练习,我正在转换 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 中可用,让我们动态呈现评论:

// 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 上的节点(状态可能会发生变化,因此我设置状态而不是 props),然后放置 Array.map() (或二维的东西)?

最佳答案

What is the idiomatic ReactJS way to deal with ?initial? state?

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

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

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

Originally I set the getInitialState() to return the data (an array of arrays) originally returned. That didn't work, as ReactJS seems to want an object and not an array

只需让您的数据成为状态的一个方面即可:

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

关于javascript - ReactJS 处理“initial”的惯用方法是什么?状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com