在反应中,在render()之前附加异步吗?

时间:2018-10-17 12:36:44

标签: reactjs async-await

我有以下代码。

searchMemberPromise() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('foo');
            }, 1000);
        });
    }

    async searchMember() {
        let out = await this.searchMemberPromise();
        return out;
    }


    async render() {

        let out = await this.searchMember();
        console.log(out);

        return (
            <Router history={history}>
            ... more code here

我尝试等待a.this.searchMember的最终结果。为此,我在render()之前附加了异步。

我得到的错误是

Uncaught Error: _default.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

我想我可以做这样的事情,但是我想删除回调样式。

let promise = this.searchMember()
promise.then((res) => { console.log(res) })

1 个答案:

答案 0 :(得分:0)

I think that you are thinking of it in the wrong way.

You want to delay rendering the html until the promise is resolved so use conditional rendering and component state.

class Component extends Component {
    state: {
        loaded: false,
        out: null
    }
    searchMemberPromise() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('foo');
            }, 1000);
        });
    }

    searchMember = async  () => {
        let out = await this.searchMemberPromise();
        this.setState({loaded: true, out});
        return;
    }
    render() {
        const { loaded, out } = this.state;
        if (!loaded) {
            return null;
        } else {
            console.log(out);
            return (
                <div>hello world</div>
            )
        }
    }
}

Please note how the searchMember method is now an arrow function so that it has access to the this reference