我正在尝试创建一个良好的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')
);
但因某种原因,当父组件状态改变时,子组件似乎没有更新。
我有什么遗漏吗?
static getDerivedStateFromProps(nextProps, prevState)
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops - GoatsWearHatscomponentWillReceiveProps
将在 17 版本中被删除。他们建议使用getDerivedStateFromProps
作为替代方案。希望能帮到大家! - Diogo Santo