javascript React:如何在将“this.state.x”用于函数之前等待数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47850047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React: How to wait data before using "this.state.x" into a function?
提问by nerotulip
I'm currently learning React, and some stuff are not so easy for a newbie...
我目前正在学习 React,有些东西对于新手来说并不那么容易......
I have a simple component which rendersthis (note that it renders a liarray thanks to function getSlots):
我有一个简单的组件renders(请注意,li由于functiongetSlots,它呈现了一个数组):
render () {
return (
<ul>
{this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
</ul>
)
}
Function getSlotsis:
功能getSlots是:
constructor (props) {...}
getSlots (viewing) {
SOME STUFF...
const monday = this.state.house.monday
return SOME STUFF...
}
componentDidMount () {...}
render () {...}
The point is that getSlotsneeds data to be fetched in componendDidMountto work. Indeed, at this time, getSlotsdoesn't work (it crashes) because it runs before data are fetched (this.state.house.mondayis "empty" when it runs).
关键是getSlots需要获取数据componendDidMount才能工作。实际上,此时,getSlots它不起作用(它崩溃),因为它在获取数据之前运行(this.state.house.monday运行时为“空”)。
How do I wait for data to be fetched before running getSlots? Thanks for your clue.
如何在运行之前等待数据被获取getSlots?谢谢你的线索。
回答by Kyle Richardson
You're going to need to conditionally render. Provide a loading state to be loaded prior to asynchronously required data. You'll want something like the following:
您将需要有条件地渲染。在异步所需数据之前提供要加载的加载状态。您将需要类似以下内容:
class WrapperComponent extends PureComponent {
constructor(props) {
super(props);
this.state = {
isLoaded: false,
data: null
};
}
componentDidMount() {
MyApiCall.then(
res => this.setState({
// using spread operator, you will need transform-object-rest-spread from babel or
// another transpiler to use this
...this.state, // spreading in state for future proofing
isLoaded: true,
data: res.data
})
);
}
render() {
const { isLoaded, data } = this.state;
return (
{
isLoaded ?
<PresentaionComponentThatRequiresAsyncData data={ data } /> :
<LoadingSpinner /> // or whatever loading state you want, could be null
}
);
}
}
回答by Maxim Saenko
constructor() {
super()
this.state = { isLoading: true }
}
componentDidMount() {
('fetch data').then(() => { this.setState({ isLoading: false }); })
}
render() {
return (
<div>
{!this.state.isLoading && ('your code')}
</div>
);
}
Something like that.
类似的东西。
回答by Prakash Sharma
You can initialize the state with empty data before fetching, in constructorlike this
您可以在获取之前使用空数据初始化状态,constructor就像这样
constructor(){
....,
this.state = { house: null}
}
And put a condition in getSlotsmethod which checks if data is fetched or not
并在getSlots方法中放置一个条件来检查是否已获取数据
getSlots (viewing) {
if (!this.state.house) {
return [];
}
SOME STUFF...
const monday = this.state.house.monday
return SOME STUFF...
}
When the data arrives, then simply set the corresponding state like this
当数据到达时,只需像这样设置相应的状态
componentDidMount(){
fetch().then((houses) => {
this.setState({ houses: houses })
})
}

