【问题标题】:How to resolve async call within componentWillMount() before render()如何在 render() 之前解决 componentWillMount() 中的异步调用
【发布时间】:2018-03-22 16:49:49
【问题描述】:

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

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)=&gt;{this.setState({foo: a})});,但无济于事。

所有这些都想问,有没有办法可以在componentWillMount() 中调用黑盒异步方法并在运行render() 之前解析结果?

【问题讨论】:

    标签: typescript react-native


    【解决方案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>
            );
        }
    }
    

    【讨论】:

    • 我见过一两件事使用这种技术,但似乎不起作用。该页面呈现空白,并且无限期地停留在那里。我以前见过bar() 工作,所以我怀疑这是方法。进一步研究其他示例异步方法以确认。
    • 这绝对是答案,bar() 表现得很古怪。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-01-02
    • 1970-01-01
    相关资源
    最近更新 更多