gpt4 book ai didi

javascript - react : How to wait data before using "this.state.x" into a function?

转载 作者:行者123 更新时间:2023-12-03 13:58:44 24 4
gpt4 key购买 nike

我目前正在学习 React,有些东西对于新手来说并不那么容易......

我有一个简单的组件,可以渲染(请注意,由于函数getSlots,它渲染了一个li数组):

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com