React Child Component Not Updating After Parent State Change

前端 未结 2 1177
忘掉有多难
忘掉有多难 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/

提交回复
热议问题