简体   繁体   中英

Resolving “Objects are not valid as a React child (found: [object Promise])” in Functional Components

I have the following in a functional component.

const [trucks, setTrucks] = React.useState([]);

React.useEffect(() => {
    Request.getTrucksForToday().then((x) => {setTrucks(x)}); // <-- this is an async function to an axios request
});

return (
...

{trucks.map((truck) =>{return<LocalShippingIcon lat={truck.latitude} lng={truck.longitude} text={truck.name}/>})}
...
);

All of the solutions I have seen for this problem suggest just putting the async function in componentDidMount() ( 1 , 2 ). Is there a way to solve it without doing this?

for completeness here is the function

export function getTrucksForToday() {
  return axios({
    method: "GET",
    url: constants.backend_url + "schedule/getTrucksForToday",
    headers: request_headers
  })
    .then(function(response) {
      console.log(response.data);
      return response.data;
    })
    .catch(function(error) {
      console.log(error);
      return error;
    });
}

Add [] to useEffect()

const [trucks, setTrucks] = React.useState([]);

React.useEffect(() => {
    Request.getTrucksForToday().then((x) => {setTrucks(x)}); // <-- this is an async function to an axios request
},[]);

return (
...

{trucks.map((truck) =>{return<LocalShippingIcon lat={truck.latitude} lng={truck.longitude} text={truck.name}/>})}
...
);

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