简体   繁体   中英

Objects are not valid as a React child (found: [object Promise]) in react render

I have a Class-based React component. This is a child component and the state comes from another parent component. This is the JSX and it is inside a map function. Inside the map function, there is a big JSX code but I am putting only the relevant part.

{platformsList.map((item, index) => (
{item.platform_id ? (
<div>
   {this.getSelectedProfiles(item.platform_id)}
</div>)) : ''}

The corresponding function is written above the render method. The response is an Object here:

getSelectedProfiles = async(id) => {
    const token = Cookie.get('user-token');
    const headers = {
      'Content-Type': 'application/json',
      authorization: token,
    };
    // Axios request  
    let response = await axios.get(`http://localhost:9999/profiles/${id}`, { headers: headers });
    console.log(response);
    return 'kkk';
  }

The error message it is showing is: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

Since, this is a child component, I don't want to store in the state of React. I want to execute this component. Is there any way to do it without storing it in the state. I am new to React and don't know where I am doing wrong.

An async function returns a promise, it does not immediately execute and return a value (in this case 'kkk' ). There does not seem to be any reason getSelectedProfiles is async either, so just remove that and make it synchronous.

  getSelectedProfiles = (id) => {
    return 'kkk';
  }

You need to await on the result from the function call:

render () {
  const getSelectedProfiles = async(id) => {
    return 'kkk';
  }
  const selectedProfiles = await getSelectedProfiles(item.platform_id);

  return {item.platform_id ? (
    <div>
     {selectedProfiles}
    </div>) : ''}

However, this has the drawback that async is blocking. If the async operation in getSelectedProfiles() is long running (such as a network request), your render will hang. In that case, you must set the state of your component instead.

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