【发布时间】:2020-01-06 12:31:13
【问题描述】:
在我的父组件中,我从 json 文件加载数据并使用它来设置状态。使用 react-router,然后我将状态传递给子组件,该子组件在路由中呈现数据。此行为按预期工作。但是,当我尝试刷新路由时,父组件的状态(以及子组件的道具)会丢失,并且页面会抛出未定义的错误。
我尝试在子组件的ComponentDidMount生命周期方法中调用父组件的数据加载函数,但应用程序抛出错误Uncaught (in promise) TypeError: this.setState is not a function。
父组件代码:
async loadWorldData() {
await axios.get("../factbook.json")
.then(res => {
let Data = res && res.data.countries;
Data = Object.values(Data).map(country => country.data) || [];
let newData = this.removeNull(Object.values(Data));
this.setState({ worldData: newData})
});
}
子组件代码:
componentWillMount = () => {
this.props.loadWorldData();
}
我不知道在不调用子生命周期方法中的父函数的情况下重新加载应用状态的另一种方法。
【问题讨论】:
-
使用
async await时不必使用promises -
你不能在componentWillMount中做
setState。请将代码移至componentDidMount -
另外,您也不需要异步等待,因为您正在更新成功的状态,而且我认为没有必要阻止这样的渲染。如果你的渲染完全依赖于这个 API,那么要么在导航到这个屏幕之前获取它,要么显示一个加载器。
标签: reactjs async-await react-router state