[英]Can't render Objects inside JSX. Throwing error Objects are not valid as a React child (found: [object Promise])
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 'value';
}
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 新手,不知道我在哪里做错了。
getSelectedProfiles
is async and returns a promise which you are trying to render in your component. getSelectedProfiles
是异步的,并返回您尝试在组件中呈现的 promise。 This is the reason react throws you the error.这就是 react 抛出错误的原因。
You must not make API calls in render function.不得在渲染 function 中调用 API。 You can separate out this logic into another component and make the API call in componentDidMount lifecycle/useEffect hook depending on what type of component you write
您可以将此逻辑分离到另一个组件中,并根据您编写的组件类型在 componentDidMount 生命周期/useEffect 挂钩中调用 API
{platformsList.map((item, index) => item.platform_id ? <Child key={index} id={item.platform_id} /> : null
}
...
const Child = ({id}) => {
const [data, setData] = useState({});
const [isLoading, setLoading] = useState(true);
useEffect(() => {
const getSelectedProfiles = async(id) => {
setLoading(true);
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);
setData({value: value}); // set the appropriate data here
setLoading(false);
}
}, [id]);
if(isLoading) return <div>Loading...</div>
// return the appropriate content here from data. Do not render the object as it is
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.