我目前正在学习 React,有些东西对新手来说并不那么容易......
我有一个简单的 renders
组件(注意,由于 函数 li
,它呈现了一个 getSlots
数组):
render () {
return (
<ul>
{this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
</ul>
)
}
函数
getSlots
是:constructor (props) {...}
getSlots (viewing) {
SOME STUFF...
const monday = this.state.house.monday
return SOME STUFF...
}
componentDidMount () {...}
render () {...}
关键是
getSlots
需要在 componendDidMount
中获取数据才能工作。实际上,此时 getSlots
不起作用(崩溃),因为它在获取数据之前运行( this.state.house.monday
在运行时为“空”)。在运行
getSlots
之前如何等待数据被获取?谢谢你的线索。 最佳答案
您将需要有条件地渲染。在异步所需数据之前提供要加载的加载状态。您将需要类似以下内容:
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
}
);
}
}
关于javascript - react : How to wait data before using "this.state.x" into a function?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47850047/