gpt4 book ai didi

reactjs - 父状态更改后,React 子组件未更新

转载 作者:行者123 更新时间:2023-12-03 12:53:47 25 4
gpt4 key购买 nike

我正在尝试制作一个漂亮的 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')
);

但由于某种原因,当父状态发生变化时,子组件似乎没有更新。

我在这里遗漏了什么吗?

最佳答案

您的代码有两个问题。

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

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

引用此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.

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

将以下代码添加到您的子组件中将解决子组件重新渲染的问题。

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

这是一个工作 fiddle :https://jsfiddle.net/o8b04mLy/

关于reactjs - 父状态更改后,React 子组件未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com