简体   繁体   English

从 this.props 渲染 React promise

[英]Render React promise from this.props

I am new to React and all this promises.我是 React 和所有这些承诺的新手。 Hence I am struggling to render promise based props in a component.因此,我正在努力在组件中渲染基于 promise 的道具。

Basically I have a single component containing all logic and required API calls.基本上我有一个包含所有逻辑和所需的 API 调用的组件。 In Render I provide a button to show and hide a modal window to display some content.在 Render 中,我提供了一个按钮来显示和隐藏模态 window 以显示一些内容。 The Content is fetched via multiple API calls which return promises -> they are stored in the state as an array of promises.内容通过多个返回承诺的 API 调用获取 -> 它们作为承诺数组存储在 state 中。

The modal window is another component and I am passing the state as props to it.模态 window 是另一个组件,我将 state 作为道具传递给它。 In the render method I.map the array from this.props into < Text > items.在 render 方法中 I.map 数组从 this.props 变成 <Text> 项。

Unfortunately this results in an error:不幸的是,这会导致错误:

Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}).错误:对象作为 React 子项无效(找到:object,键为 {_U, _V, _W, _X})。 If you meant to render a collection of children, use an array instead.如果您打算渲染子集合,请改用数组。

As far as I understand this error, react is trying to render the Promise object itself instead of the result of the API call in the parent component.据我了解这个错误,反应试图呈现 Promise object 本身,而不是父组件中 API 调用的结果。

How can I render a promise which passed a props to a component?我如何渲染将道具传递给组件的 promise?

I created a sample on codesandbox simulating what I am trying to do: https://codesandbox.io/s/crazy-microservice-fcgoy?file=/src/modal_component.js我在 codesandbox 上创建了一个示例来模拟我正在尝试做的事情: https://codesandbox.io/s/crazy-microservice-fcgoy?file=/src/modal_component.js

You have to handle the returned promise, like so:您必须处理返回的 promise,如下所示:

buttonOnClick() {
    const ids = [1, 2, 3, 4, 5];
    const resolvedNamesPromises = ids.map((element) => {
        // resolveName returns a promise  
        return this.resolveName(element);
    });

    Promise.all(resolvedNamesPromises).then(names => {
        this.setState({
            modal: {
                 show: true,
                 names
            }
        });
    });
  }

I suggest learning more about promises by reading here .我建议通过阅读此处了解更多关于承诺的信息。 Also here's the Promise.all reference docs.这里还有Promise.all参考文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM