我正在尝试制作一个不错的 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')
);
但由于某种原因,当父状态发生变化时,子组件似乎没有更新。
我在这里错过了什么吗?
原文由 Vinnie James 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码有两个问题。
您的子组件的初始状态是从 props 设置的。
引用此 SO 答案:
所以如果你无法避免这种情况,理想的解决方案是使用方法
componentWillReceiveProps
来监听新的道具。将以下代码添加到您的子组件将解决您的子组件重新渲染问题。
第二个问题是
fetch
。这是一个工作小提琴: https ://jsfiddle.net/o8b04mLy/