简体   繁体   中英

Render React promise from this.props

I am new to React and all this promises. Hence I am struggling to render promise based props in a component.

Basically I have a single component containing all logic and required API calls. In Render I provide a button to show and hide a modal window to display some content. The Content is fetched via multiple API calls which return promises -> they are stored in the state as an array of promises.

The modal window is another component and I am passing the state as props to it. In the render method I.map the array from this.props into < Text > items.

Unfortunately this results in an error:

Error: Objects are not valid as a React child (found: object with keys {_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.

How can I render a promise which passed a props to a component?

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

You have to handle the returned promise, like so:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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