我有这样的东西,我想从直接在其上方初始化的变量创建状态数组。我收到错误卡片未定义
。有没有解决的办法?我需要在状态中专门设置这个数组。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: [
{
name: "Name 1",
description: "dfdsfaf",
},
{
name: "Name 2",
description: "dsfsfasf",
},
{
name: "Name 3",
description: "daslkdjadlajsd",
},
],
names: cards.map(item => item.name)
};
}
...
}
最佳答案
您可以在 JavaScript 中执行此操作,如下所示:
const cards = [...]
const names = = cards.map(...)
this.state = { cards: cards, names: names }
您可能不应该这样做,并将状态仅设置为卡片并将计算名称的调用移至渲染方法
关于javascript - react /JSX : Can I use a state variable in another state variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60118726/