React报错:Objects are not valid as a React child 及Props传递疑问
解决React组件异步报错+组件Props传递指南
先解决你的异步组件报错问题
你当前的错误核心原因是React组件不能是async函数——async函数执行后返回的是Promise对象,而React要求组件必须返回React元素、null这类可渲染内容,Promise被当成了无效的React子元素,因此触发报错。
修改后的正确代码如下:
import React, { useEffect, useState } from "react"; import getConfig from 'next/config'; import axios from "axios"; const { publicRuntimeConfig } = getConfig(); export default function FooterAjax() { // 用state存储请求数据 const [trendingTopicHeader, setTrendingTopicHeader] = useState(null); // 管理加载/错误状态 const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await axios.get(`${publicRuntimeConfig.nodeLocal}getRedisData/NEWS18:new_fms_system`); setTrendingTopicHeader(response.data); console.log("hello =", JSON.stringify(response.data)); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, []); // 空依赖数组确保请求仅在组件挂载时执行一次 // 根据状态渲染对应内容 if (loading) return <div>加载中...</div>; if (error) return <div>请求出错:{error.message}</div>; return ( <div> <h1>navreet</h1> {/* 可在这里渲染请求回来的数据 */} {trendingTopicHeader && <p>{JSON.stringify(trendingTopicHeader)}</p>} </div> ); }
组件中传递Props的常用方式
1. 父组件向子组件传递Props
这是最基础的传递方式,父组件在引用子组件时直接附加属性:
// 子组件 FooterAjax export default function FooterAjax(props) { return <h1>{props.title}</h1>; } // 父组件 import FooterAjax from './FooterAjax'; export default function ParentComponent() { return <FooterAjax title="navreet" />; }
也可以用解构赋值简化子组件代码:
export default function FooterAjax({ title }) { return <h1>{title}</h1>; }
2. 子组件向父组件传递数据(反向传值)
通过父组件传递回调函数给子组件,子组件调用该函数传递数据:
// 子组件 export default function FooterAjax({ onDataLoaded }) { useEffect(() => { const fetchData = async () => { const response = await axios.get('请求地址'); // 调用父组件的回调函数,传递数据 onDataLoaded(response.data); }; fetchData(); }, [onDataLoaded]); return <h1>加载中...</h1>; } // 父组件 export default function ParentComponent() { const handleDataLoaded = (data) => { console.log('子组件传回的数据:', data); }; return <FooterAjax onDataLoaded={handleDataLoaded} />; }
3. 跨多层组件传递Props(避免Prop Drilling)
如果组件层级较深,不想逐层传递Props,可以使用React Context:
// 创建Context import { createContext, useContext, useState } from 'react'; const AppContext = createContext(); // 父组件作为Context Provider export default function ParentComponent() { const [theme, setTheme] = useState('light'); return ( <AppContext.Provider value={{ theme, setTheme }}> <FooterAjax /> </AppContext.Provider> ); } // 子组件直接通过useContext获取数据 export default function FooterAjax() { const { theme } = useContext(AppContext); return <h1 style={{ color: theme === 'light' ? '#000' : '#fff' }}>navreet</h1>; }
内容的提问来源于stack exchange,提问作者navdhiman
相关产品推荐
相关产品推荐

