【问题标题】:Can't render Objects inside JSX. Throwing error Objects are not valid as a React child (found: [object Promise])无法在 JSX 中渲染对象。抛出错误对象作为 React 子级无效(发现:[object Promise])
【发布时间】:2020-06-19 05:18:10
【问题描述】:

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

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

对应的函数写在render方法上面。这里的响应是一个对象:

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 的状态中。我想执行这个组件。有没有办法在不将其存储在状态中的情况下做到这一点。我是 React 新手,不知道我在哪里做错了。

【问题讨论】:

    标签: javascript reactjs promise


    【解决方案1】:

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

    您不得在渲染函数中进行 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 
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-02
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2016-10-26
      相关资源
      最近更新 更多