如何在render()之前解决componentWillMount()中的异步调用

时间:2018-03-22 16:49:50

标签: typescript react-native

尝试在调用componentWillMount()方法之前弄清楚如何在render()中调用异步函数。我有以下代码(为简单起见而删除):

interface State {
    foo?: AClass
}
export class BClass extends React.Component<Props, State>
{
    async componentWillMount(){
        await this.run();
    }
    async run(){
        let a = await bar();
        this.setState({foo: a});
    }
    render() {
        return (
            <View>
                <Text> {this.state.foo == null ? "null" : this.state.foo.getText()} </Text>
            </View>
        );
    }
}

我已经看到了一个涉及向loading添加this.state变量的潜在解决方案,但这并没有做多少。我还尝试过回复Promise,然后做fooPromise.then((c)=>{this.setState({foo: a})});,但无济于事。

这一切要问,有没有办法在componentWillMount()中调用blackbox异步方法并在运行render()之前解析结果?

1 个答案:

答案 0 :(得分:1)

你可以让它在完成之前不做任何渲染:

export class BClass extends React.Component<Props, State>
{
    state = {
      loaded: false,
    }
    async componentWillMount(){
        await this.run();
    }
    async run(){
        let a = await bar();
        this.setState({ foo: a, loaded: true });
    }
    render() {
        return (
            <View>
                {this.state.loaded &&
                  <Text> {this.state.foo == null ? "null" : this.state.foo.getText()} </Text>
                }
            </View>
        );
    }
}