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

标签 javascript reactjs asynchronous

我目前正在学习 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/

相关文章:

javascript - 无法在 React 中更改类

node.js - 如何从NodeJS中的函数返回Post请求的响应?

javascript - 如何让 learnyounode #9 杂耍异步工作

javascript - 更改react-chartjs 2中的工具提示方向

javascript - React-router-dom - 链接更改 url 但不呈现

reactjs - 围绕 Angular2 的架构模式 : Redux, Flux、React、Reactive、RxJS、Ngrx、MVI、

javascript - 延迟广告脚本直到所有其他 JS 加载完毕?

javascript - Nodejs 串联运行函数

javascript - 发生错误后,Axios “get”仍会转到 “then”

javascript - jQuery - 向下滑动面板