【问题标题】:React, Typescript, and PromisesReact、Typescript 和 Promise
【发布时间】:2016-12-29 14:25:31
【问题描述】:

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

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

目前我有以下代码:

componentWillMount() {
    let fooProps = listGetter.returnListData().then((response) => {
        return response;
    });
}

public render(): JSX.Element {
    <div>
        <Foo ElementProperties={this.fooProps} />
    </div>
}

但是,此代码出错并显示“无法将空值分配给属性”。

我做错了什么?处理 Promise 并将其解析为 REACT 组件的最佳方法是什么?

谢谢!

【问题讨论】:

  • 在 then 回调中检查返回的列表是否为空/null。另外,你的 fooProps 是块作用域的,所以你的渲染函数看不到它。

标签: javascript reactjs typescript promise


【解决方案1】:

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})
}

【讨论】:

  • 这里不需要使用bind,因为箭头函数保持this的范围。
  • @NitzanTomer 我刚刚添加了一条评论,当然不需要,但习惯是件好事,特别是如果您使用不同的函数语法。我什至会在构造函数中推荐this.updateComponent = this.updateComponent.bind(this)
  • 它是多余的,无缘无故地创建了一个新函数
【解决方案2】:

您应该使用组件的the state
更改状态会导致组件重新渲染,就像组件更改子组件的属性会导致子组件重新渲染一样。

类似:

componentWillMount() {
    listGetter.returnListData().then((response) => {
        this.setState({
            fooProps: response.fooProps
        });
    });
}

public render(): JSX.Element {
    <div>
        <Foo ElementProperties={ this.state.fooProps } />
    </div>
}

【讨论】:

  • 非常感谢尼赞。这正是我想要的。我没有检查 null 并且在返回响应之前,render 方法开始执行将 null 传递到 Foo 控件并呈现 null 引用除外。我对其进行了重新设计,并将状态绑定到函数,现在它工作得很好。
猜你喜欢
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2020-03-21
  • 2020-04-24
相关资源
最近更新 更多