且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

父状态更改后反应子组件未更新

更新时间:2023-02-12 07:45:40

您的代码有两个问题.

子组件的初始状态是通过 props 设置的.

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

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

引用此 SO 答案:

将初始状态作为 prop 传递给组件是一种反模式因为 getInitialState(在我们的例子中是构造函数)方法只在第一次调用组件渲染.再也不会了.这意味着,如果你重新渲染组件传递一个不同值作为prop,组件不会做出相应的反应,因为组件会保持状态从它第一次被渲染开始.这很容易出错.

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.

因此,如果您无法避免这种情况,理想的解决方案是使用方法 componentWillReceiveProps 监听新的 props.

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 });  
}

第二个问题是 fetch.

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

这是一个有效的小提琴:https://jsfiddle.net/o8b04mLy/

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