React component not re-rendering on state change

后端 未结 7 801
抹茶落季
抹茶落季 2021-02-02 05:59

I have a React Class that\'s going to an API to get content. I\'ve confirmed the data is coming back, but it\'s not re-rendering:

var DealsList = React.createCla         


        
7条回答
  •  孤街浪徒
    2021-02-02 06:42

    After looking into many answers (most of them are correct for their scenarios) and none of them fix my problem I realized that my case is a bit different:

    In my weird scenario my component was being rendered inside the state and therefore couldn't be updated. Below is a simple example:

    constructor() {
        this.myMethod = this.myMethod.bind(this);
        this.changeTitle = this.changeTitle.bind(this);
    
        this.myMethod();
    }
    
    changeTitle() {
        this.setState({title: 'I will never get updated!!'});
    }
    
    myMethod() {
        this.setState({body: 
    {this.state.title}
    }); } render() { return <> {this.state.body} }

    After refactoring the code to not render the body from state it worked fine :)

提交回复
热议问题