[英]Objects are not valid as a React child (found: [object Promise]) in react render
I have a Class-based React component.我有一个基于类的 React 组件。 This is a child component and the state comes from another parent component.
这是一个子组件,state 来自另一个父组件。 This is the JSX and it is inside a map function.
这是 JSX,它位于 map function 内。 Inside the map function, there is a big JSX code but I am putting only the relevant part.
在 map function 里面,有一个很大的 JSX 代码,但我只放了相关部分。
{platformsList.map((item, index) => (
{item.platform_id ? (
<div>
{this.getSelectedProfiles(item.platform_id)}
</div>)) : ''}
The corresponding function is written above the render method.对应的function写在render方法上面。 The response is an Object here:
这里的响应是 Object:
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]).它显示的错误消息是:错误:对象作为 React 子项无效(找到:[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.因为,这是一个子组件,我不想存储在 React 的 state 中。 I want to execute this component.
我想执行这个组件。 Is there any way to do it without storing it in the state.
有没有办法不将其存储在 state 中。 I am new to React and don't know where I am doing wrong.
我是 React 新手,不知道我在哪里做错了。
An async function returns a promise, it does not immediately execute and return a value (in this case 'kkk'
).异步 function 返回 promise,它不会立即执行并返回值(在本例中为
'kkk'
)。 There does not seem to be any reason getSelectedProfiles
is async either, so just remove that and make it synchronous.似乎也没有任何理由
getSelectedProfiles
是异步的,因此只需将其删除并使其同步即可。
getSelectedProfiles = (id) => {
return 'kkk';
}
You need to await
on the result from the function call:您需要
await
function 调用的结果:
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.但是,这具有
async
阻塞的缺点。 If the async operation in getSelectedProfiles()
is long running (such as a network request), your render will hang.如果
getSelectedProfiles()
中的异步操作长时间运行(例如网络请求),您的渲染将挂起。 In that case, you must set the state of your component instead.在这种情况下,您必须改为设置组件的 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.