gpt4 book ai didi

javascript - this.state 在 .map 里面是 0

转载 作者:行者123 更新时间:2023-11-30 20:28:08 25 4
gpt4 key购买 nike

我正在尝试将所有选定的项目 ID 从 redux 存储转换为项目名称并将其保存到状态中。

我的问题是 setState 函数内的扩展运算符等于零。我必须将函数的上下文绑定(bind)到类吗?

  constructor(props) {
super(props);
this.state = {
item_Name: []
};
}




componentDidMount() {
this.props.Cart_Items.Id.map((item, i) => {
if (item === "001") {
// The problem is that this.state.item_Name is 0
console.log(this.state.item_Name)
this.setState({
item_Name: [...this.state.item_Name, "Buddha"]
});
}
})
}

感谢您的帮助!

最佳答案

setState 是异步的,会批量更新。
另一件事,.map 正在返回一个数组,因此只需将新数组存储在一个变量中并将其传递给 setState

P.S,您正在检查 .map 中的条件。但是 .map 应该返回相同数量的成员,添加一个 else 或者只使用 .filter.reduce .

  componentDidMount() {
const nextState = this.props.Cart_Items.Id.map((item, i) => {
if (item === "001") {
return "Buddha"
}
// you need an else here because map should return the same number of members, or use .filter or .reduce
})
this.setState({item_name: nextstate});
}

关于javascript - this.state 在 .map 里面是 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50657212/

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