programing tip

부모 상태 변경 후 React 자식 구성 요소가 업데이트되지 않음

itbloger 2020. 10. 5. 07:43
반응형

부모 상태 변경 후 React 자식 구성 요소가 업데이트되지 않음


다양한 하위 구성 요소에 데이터를 채우기 위해 멋진 ApiWrapper 구성 요소를 만들려고합니다. 내가 읽은 모든 것에서 이것은 작동합니다 : https://jsfiddle.net/vinniejames/m1mesp6z/1/

class ApiWrapper extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      response: {
        "title": 'nothing fetched yet'
      }
    };
  }

  componentDidMount() {
    this._makeApiCall(this.props.endpoint);
  }

  _makeApiCall(endpoint) {
    fetch(endpoint).then(function(response) {
      this.setState({
        response: response
      });
    }.bind(this))
  }

  render() {
    return <Child data = {
      this.state.response
    }
    />;
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: props.data
    };
  }

  render() {
    console.log(this.state.data, 'new data');
    return ( < span > {
      this.state.data.title
    } < /span>);
  };
}

var element = < ApiWrapper endpoint = "https://jsonplaceholder.typicode.com/posts/1" / > ;

ReactDOM.render(
  element,
  document.getElementById('container')
);

그러나 어떤 이유로 부모 상태가 변경 될 때 자식 구성 요소가 업데이트되지 않는 것 같습니다.

여기에 뭔가 빠졌나요?


코드에 두 가지 문제가 있습니다.

자식 구성 요소의 초기 상태는 소품에서 설정됩니다.

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

SO 응답 에서 인용 :

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/


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.

참고URL : https://stackoverflow.com/questions/41233458/react-child-component-not-updating-after-parent-state-change

반응형