问题描述
我正在尝试制作一个不错的 ApiWrapper 组件来填充各种子组件中的数据.从我读过的所有内容来看,这应该有效:https://jsfiddle.net/vinniejames/m1mesp6z/1/
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/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')
);
但是由于某种原因,当父状态发生变化时,子组件似乎没有更新.
But for some reason, it seems the child component is not updating when the parent state changes.
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
您的代码有两个问题.
子组件的初始状态是通过 props 设置的.
Your child component's initial state is set from props.
this.state = {
data: props.data
};
引用此 SO 答案:
将初始状态作为 prop
传递给组件是一种反模式因为 getInitialState
(在我们的例子中是构造函数)方法只在第一次调用组件渲染.再也不会了.这意味着,如果你重新渲染组件传递一个不同值作为prop
,组件不会做出相应的反应,因为组件会保持状态从它第一次被渲染开始.这很容易出错.
因此,如果您无法避免这种情况,理想的解决方案是使用方法 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/
这篇关于父状态更改后反应子组件未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!