Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 此.state在.map中为0_Javascript_Reactjs - Fatal编程技术网

Javascript 此.state在.map中为0

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) =&

Iam正在尝试将所有选定的项目id从redux存储转换为项目名称,并将其保存到状态

我的问题是setState函数中的spread运算符等于零。我必须将函数的上下文绑定到类吗

  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});
  }

这回答了你的问题吗?