繁体   English   中英

无法在 JSX 中渲染对象。 抛出错误对象作为 React 子对象无效(发现:[object Promise])

[英]Can't render Objects inside JSX. Throwing error Objects are not valid as a React child (found: [object Promise])

我有一个基于类的 React 组件。 这是一个子组件,state 来自另一个父组件。 这是 JSX,它位于 map function 内。 在 map function 里面,有一个很大的 JSX 代码,但我只放了相关部分。

{platformsList.map((item, index) => (
{item.platform_id ? (
<div>
   {this.getSelectedProfiles(item.platform_id)}
</div>)) : ''}

对应的function写在render方法上面。 这里的响应是 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';
  }

它显示的错误消息是:错误:对象作为 React 子项无效(找到:[object Promise])。 如果您打算渲染一组子项,请改用数组。

因为,这是一个子组件,我不想存储在 React 的 state 中。 我想执行这个组件。 有没有办法不将其存储在 state 中。 我是 React 新手,不知道我在哪里做错了。

getSelectedProfiles是异步的,并返回您尝试在组件中呈现的 promise。 这就是 react 抛出错误的原因。

不得在渲染 function 中调用 API。 您可以将此逻辑分离到另一个组件中,并根据您编写的组件类型在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM