【发布时间】:2018-06-14 20:29:36
【问题描述】:
在更新 Child 组件的状态时,我需要更新父组件 (App.js) 的状态,其中我在 componentDidMount() 中执行 GET 请求。
我尝试将函数 setPoints 作为道具传递,但不幸的是这不起作用。
这是我尝试过的:
Child 组件:
class Child extends Component {
state = {
points: null
}
async componentDidMount() {
try {
const res = await axios.get(url);
const data = res.data;
this.setState({
points: data.points,
})
this.props.setPoints();
} catch (err) {
console.log('child', err);
}
}
render() {
return (
<div>
</div>
);
}
}
父组件(App):
class App extends Component {
state = {
points: '',
}
setPoints() {
this.setState({
...this.state,
points: this.state.points
});
}
shouldComponentUpdate(nextState) {
if (this.state.points !== nextState.points) {
return true;
}
return false;
}
render() {
return (
<div className="App">
<Route exact path="/child" render={() => <Child setPoints={this.setPoints} />} />
</div>
);
}
}
谁能帮我解决这个问题?非常感谢您的帮助。
编辑
我尝试了 Joe Clay 所写的内容,这非常合理,但我仍然发现了一个错误。这是我更新的代码:
async componentDidMount() {
try {
const res = await axios.get(url);
const data = res.data;
console.log(data.points);
this.props.setPoints(data.points);
} catch (err) {
console.log('child', err);
}
它确实记录了点的值,但由于某种原因,我得到:“无法读取未定义的属性‘点’”。
【问题讨论】:
-
请阅读 React 文档网站上的 Lifting State Up 和 Thinking in React。将相同的状态存储在两个单独的组件中几乎总是表明您以错误的方式处理事情 - 惯用的 React 代码通常对于任何给定的数据都有“单一事实来源”。
-
另外请阅读关于使用更新函数reactjs.org/docs/react-component.html#setstate根据当前状态计算的设置状态
标签: reactjs async-await parent-child react-props