React, Typescript, and Promises

React, Typescript, and Promises

本文关键字:Promises and Typescript React      更新时间:2023-09-26

我正在尝试编写调用web服务的组件,并通过承诺异步返回一些数据。一旦解决了这个问题,我想在我的组件的渲染方法中包含结果。理想情况下,我想我希望的承诺被传递到另一个组件的结果。即;承诺的结果是一个项目列表。

还有一件事-我正在使用Typescript编写这个React组件。

目前我有以下代码:

componentWillMount() {
    let fooProps = listGetter.returnListData().then((response) => {
        return response;
    });
}
public render(): JSX.Element {
    <div>
        <Foo ElementProperties={this.fooProps} />
    </div>
}

然而,这段代码出错并显示"cannot assign null value to property"。

我做错了什么?什么是最好的方式来处理承诺和解决他们成组件在REACT?

谢谢!

你应该使用组件的状态。
改变状态会导致组件的重新呈现,就像组件改变子组件的属性会导致子组件被重新呈现一样。

类似:

componentWillMount() {
    listGetter.returnListData().then((response) => {
        this.setState({
            fooProps: response.fooProps
        });
    });
}
public render(): JSX.Element {
    <div>
        <Foo ElementProperties={ this.state.fooProps } />
    </div>
}

promise永远不会返回它们的值,它们只返回一个Thenable,所以你可以链接它们。您正在寻找的返回值将在传递给then的函数的第一个参数中

componentWillMount() {
    // bind the function to `this` so even if you don't use an
    // anonymous arrow function this call will work in the right context
    let updateComponent = this.updateComponent.bind(this);
    listGetter.returnListData().then((res) => {
        updateComponent(res);
    })
}
updateComponent(res) {
    this.setState({fooProps: res.fooProps})
}