简体   繁体   English

解决功能组件中的“对象作为 React 子级无效(找到:[object Promise])”

[英]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 ).我为这个问题看到的所有解决方案都建议将异步 function 放在componentDidMount() ( 1 , 2 ) 中。 Is there a way to solve it without doing this?有没有办法在不这样做的情况下解决它?

for completeness here is the function为了完整起见,这里是 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()[]添加到 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}/>})}
...
);

暂无
暂无

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

相关问题 对象作为 React 子级无效(发现:[object Promise]) - Objects are not valid as a React child (found: [object Promise]) 对象无效,无法作为React子对象(找到:[object Promise]) - Objects not valid as a React child (found: [object Promise]) React 错误“对象作为 React 子项无效(找到:[object Promise])” - React error "Objects are not valid as a React child (found: [object Promise])" 对象在反应渲染中作为 React 子级无效(找到:[object Promise]) - Objects are not valid as a React child (found: [object Promise]) in react render 错误:对象在 reactjs 中作为 React 子对象无效(找到:[object Promise]) - Error: Objects are not valid as a React child (found: [object Promise]) in reactjs Redux:对象作为 React 子项无效(找到:[object Promise]) - Redux: Objects are not valid as a React child (found: [object Promise]) 对象作为尝试返回 swal 的 React 子项(找到:[object Promise])无效 - Objects are not valid as a React child (found: [object Promise]) trying to return swal 我收到一个错误:对象作为 React 子对象无效(找到:[object Promise]) - I got an Error: Objects are not valid as a React child (found: [object Promise]) 如何修复错误:对象作为 React 子对象无效(找到:[object Promise]) - How to fix Error: Objects are not valid as a React child (found: [object Promise]) 对象作为 React 子对象无效 [object Promise] - Objects are not valid as a React child [object Promise]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM