Javascript 此.state在.map中为0
Iam正在尝试将所有选定的项目id从redux存储转换为项目名称,并将其保存到状态 我的问题是setState函数中的spread运算符等于零。我必须将函数的上下文绑定到类吗Javascript 此.state在.map中为0,javascript,reactjs,Javascript,Reactjs,Iam正在尝试将所有选定的项目id从redux存储转换为项目名称,并将其保存到状态 我的问题是setState函数中的spread运算符等于零。我必须将函数的上下文绑定到类吗 constructor(props) { super(props); this.state = { item_Name: [] }; } componentDidMount() { this.props.Cart_Items.Id.map((item, i) =&
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
另外,您正在检查.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});
}
这回答了你的问题吗?