更改状态变量的状态后如何重新呈现页面?

时间:2019-11-10 17:17:48

标签: javascript reactjs

我在按下按钮时在reactjs中设置状态变量的状态。我调用以下过程(实际上正在调用)。

nextSuggestion() {
        console.log(this.state.suggestions_index);
        this.state.suggestions_index = this.state.suggestions_index + 1;
        console.log(this.state.suggestions_index);
    }

即使我具有以下componentDidMount(),也会调用上述函数,并且不会重新呈现页面:

async componentDidMount(){

        const query = new URLSearchParams(this.props.location.search);

        const token = query.get('token');


        const url = "http://www.mocky.io/v2/" + token;


        this.setState({url_prod: url});    

        const response = await fetch(url);
        const data = await response.json();
        this.setState({produto: data.suggestions[this.state.suggestions_index], loading_produto: false})
        this.setState({alternativas: data.choices, loading_alternativas: false})
        this.setState({atributos: data.suggestions[this.state.suggestions_index].product_data.attributes, loading_atributos: false})

    }

通过以下代码在render()函数中创建按钮:

  if(!this.state.loading_alternativas){

    this.texts = lista_alternativas.map((text, key) => {


        return  <div id="center-button"><button type="button" className="btn btn-primary" key={text.id} onClick={this.nextSuggestion.bind(this)}>{text.text}</button></div>
    });
}

状态:

state = {
        produto: null,
        alternativas: null,
        atributos: [],
        suggestions_index: 0,
        loading_produto: true,
        loading_alternativas: true,
        loading_atributos: true,
        showPopupDescProd: false,
        showPopupAnswer: false,
        url_prod: null,
    };

要使它正常工作,我缺少什么?

1 个答案:

答案 0 :(得分:4)

您正在改变状态:

this.state.suggestions_index = this.state.suggestions_index + 1;

这是一件坏事。更具体地说,ReactJS框架不希望使用它,因此没有理由重新渲染。

不直接设置状态值。使用新的状态对象更新状态。例如:

this.setState((prevState) => ({
    suggestions_index: prevState.suggestions_index + 1
}));

调用setState()通知框架将当前状态替换为新状态,并在适用时触发重新呈现。


编辑:作为对Andy's comment的回应(感谢Andy,我从中学到了新知识!),还请注意setState()本质上是异步的。由于您希望在设置状态后登录到控制台,因此您希望在回调中进行操作。例如:

const newState = {
    ...this.state
    suggestions_index: this.state.suggestions_index + 1
};
this.setState(newState, () => console.log(this.state.suggestions_index));

(尽管我怀疑您的console.log只是临时用于调试,可能会被删除,所以您只需省略回调。)