React Child Component Not Updating After Parent State Change

前端 未结 2 1165
忘掉有多难
忘掉有多难 2020-12-04 07:41

I\'m attempting to make a nice ApiWrapper component to populate data in various child components. From everything I\'ve read, this should work: https://jsfiddle.net/vinnieja

相关标签:
2条回答
  • 2020-12-04 08:13

    There are two issues with your code.

    Your child component's initial state is set from props.

    this.state = {
      data: props.data
    };
    

    Quoting from this SO Answer:

    Passing the intial state to a component as a prop is an anti-pattern because the getInitialState (in our case the constuctor) method is only called the first time the component renders. Never more. Meaning that, if you re-render that component passing a different value as a prop, the component will not react accordingly, because the component will keep the state from the first time it was rendered. It's very error prone.

    So if you can't avoid such a situation the ideal solution is to use the method componentWillReceiveProps to listen for new props.

    Adding the below code to your child component will solve your problem with Child component re-rendering.

    componentWillReceiveProps(nextProps) {
      this.setState({ data: nextProps.data });  
    }
    

    The second issue is with the fetch.

    _makeApiCall(endpoint) {
      fetch(endpoint)
        .then((response) => response.json())   // ----> you missed this part
        .then((response) => this.setState({ response }));
    }
    

    And here is a working fiddle: https://jsfiddle.net/o8b04mLy/

    0 讨论(0)
  • 2020-12-04 08:13

    There are some things you need to change.

    When fetch get the response, it is not a json. I was looking for how can I get this json and I discovered this link.

    By the other side, you need to think that constructor function is called only once.

    So, you need to change the way that you retrieve the data in <Child> component.

    Here, I left an example code: https://jsfiddle.net/emq1ztqj/

    I hope that helps.

    0 讨论(0)
提交回复
热议问题