[英]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.