使用setState ReactJs更新状态

时间:2019-03-04 10:31:56

标签: javascript reactjs redux

我试图在单击按钮时更新状态变量。但是我的问题是,它使用正确的数据更新一次,然后再次使用构造函数定义的数据更新。

    constructor(props) {
        super(props);
        this.state = {
            popupshow: [{ check: false, id: '' }]

        }
    }

componentDidUpdate(prevProps, prevState) {
         console.log("this.state.popupshow",this.state.popupshow)

    }


Details(type){
   this.state.popupshow[i].id = type
   this.state.popupshow[i].check = true;

   this.setState({ popupshow: this.state.popupshow });
}

render() {
return (
  <a onClick={() => this.Details("Tv Series")}>Update </>
)
}

我的console.log像下面这样

enter image description here

3 个答案:

答案 0 :(得分:1)

我认为您应该重写如下详细功能:

Details(type, i){
   const popupDetail = Object.assign([], this.state.popupshow);
   popupDetail[i].id = type
   popupDetail[i].check = true;

   this.setState({ popupshow: popupDetail });
}

您正在设置popupshow:this.state.popupshow这将导致forceupdate重新渲染组件,因此其值将被重置。

答案 1 :(得分:1)

您不应直接更新React状态。您应该始终通过setState方法来更新/设置React状态。

这些行违反了React主体

this.state.popupshow[i].id = type
this.state.popupshow[i].check = true;

如下更新您的Details

Details(type){
   let { popupshow } = this.state;
   let i = 0;
   popupshow[i].id = type
   popupshow[i].check = true;

   this.setState({ popupshow });
}

请注意,我没有变量i的概念,因此假设变量为0

答案 2 :(得分:0)

我完全同意为该问题提供的其他答案,但是有几点值得注意,因为您可能想将函数添加到上下文中。 支持将这些行添加到构造函数的观点是,每个类的实例仅创建一次新的绑定函数。您也可以使用

onClick={this.Details.bind(this, "Tv Series")}

或(ES6):

onClick={() => this.Details("Tv Series")} 但是这两种方法中的任何一种都会在每次重新渲染组件时创建一个新函数。

然后也将功能更改为箭头功能

Details(type, i){
   const popupDetail = Object.assign([], this.state.popupshow);
   popupDetail[i].id = type
   popupDetail[i].check = true;

   this.setState({ popupshow: popupDetail });
}
相关问题