gpt4 book ai didi

reactjs - React 入门教程 : how do list's keys get their value?

转载 作者:行者123 更新时间:2023-12-02 00:50:03 24 4
gpt4 key购买 nike

我没有js经验,建议先学React,再学React Native。我的问题来自 Intro to React's tutorial 的代码.

在教程中,我们创建了一个名为 history 的列表,move 作为其 key

class Game extends React.Component {
constructor() {
super();
this.state = {
history: [{
squares: Array(9).fill(null)
}],
xIsNext: true,
stepNumber: 0,
};
}

[...]

render() {
[...]

const moves = history.map((step, move) => {
const desc = move ?
'Move #' + move :
'Game start';
return (
<li key={move}>
<a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
</li>
);
});

[...]

那部分的解释是

[...] React asks you to specify a key property on each element in a list, a string to differentiate each component from its siblings. In this case, alexa, ben, claudia might be sensible keys; if the items correspond to objects in a database, the database ID is usually a good choice:

<li key={user.id}>{user.name}: {user.taskCount} tasks left</li>

[...] It's strongly recommended that you assign proper keys whenever you build dynamic lists. If you don't have an appropriate key handy, you may want to consider restructuring your data so that you do. [...] If you don't specify any key, React will warn you and fall back to using the array index as a key – [...]

现在让我感到困惑的是,上面history 上的move 是什么?我看不到任何暗示 move 被分配了一个值,但是当它被打印时,它显示列表索引?怎么会?

最佳答案

列表是通过使用map 方法“映射”history 数组创建的。 map 将为数组中的每个元素调用一个函数;此回调函数的第二个参数是数组中元素的索引。

在您的代码中,回调函数如下所示:

(step, move) => {
const desc = move ?
'Move #' + move :
'Game start';
return (
<li key={move}>
<a href="#" onClick={() => this.jumpTo(move)}>{desc}</a>
</li>
);
}

因此数组的索引,即第二个参数,被称为move(你可以随便叫它);然后将其值呈现为每个列表项的关键属性。

Description of map here

关于reactjs - React 入门教程 : how do list's keys get their value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584266/

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