React组件无法渲染服务器返回数据,页面显示null
问题描述
在React组件页面中尝试渲染服务器返回的recoveryCodes数据,但页面始终显示null/空值。fetchRecoveryCodes函数里的alert能正常展示获取到的服务器数据,却无法在页面渲染。
相关代码
export function authentication() { const [error, setError] = useState(null) const [recoveryCodes, setRecoveryCodes] = useState(null); const [isLoading, setIsLoading] = useState(true); const router = useRouter(); const searchParams = useSearchParams() async function verify() { try { const userId = searchParams.get('userId'); const secret = searchParams.get('secret'); await axios.get('/api/currentuser', { withCredentials: true }) await axios.post('/api/verifyemail', { userId, secret }) router.replace('/emailmfa'); } catch (error: any) { setError(error) alert(JSON.stringify(error)) alert('Verification failed') } }; const fetchRecoveryCodes = async () => { try { const response = await axios.get('/api/otp', { withCredentials: true }); alert(response.data) setRecoveryCodes(response.data); setIsLoading(false) } catch (error: any) { alert(JSON.stringify(error.response.data.detail)); setError(error.response.data.detail); setIsLoading(false) } }; useEffect(() => { fetchRecoveryCodes() }, []); return ( <div className="flex h-screen w-screen justify-center items-center justify-items-center"> <div className="w-[400px]"> <Card> <CardHeader> <CardTitle> Email OTP and verifcation</CardTitle> <CardDescription> These recovery codes can only be generated ONCE. Please save them in a secure place </CardDescription> </CardHeader> <CardContent> { isLoading ? 'loading' : error ? <p>{error}</p> : <p>{JSON.stringify(recoveryCodes)}</p> } </CardContent> <CardFooter> </CardFooter> <div className="flex p-4 justify-center"> <Button variant="outline" onClick={verify}>Verify me!</Button> </div> </Card> </div> </div> ) } export default authentication;
问题排查与解决
核心修复:移除组件的
async修饰符
React函数组件不能是异步函数,异步组件会返回Promise而非React元素,导致React无法正确渲染组件,状态更新也无法触发重渲染。直接去掉async function authentication()中的async即可。数据渲染格式调整
如果recoveryCodes是数组或对象类型,直接用<p>{recoveryCodes}</p>会显示[object Object]或数组的默认字符串形式,无法展示具体内容。可以改为JSON.stringify(recoveryCodes)查看完整数据结构,或根据实际数据类型遍历渲染:// 示例:如果recoveryCodes是数组 {recoveryCodes.map((code, index) => ( <p key={index}>{code}</p> ))}额外验证点
在组件顶部添加console.log('当前recoveryCodes:', recoveryCodes),确认setRecoveryCodes调用后状态是否正确更新;同时检查response.data的实际结构,确保渲染逻辑匹配数据格式。
内容的提问来源于stack exchange,提问作者C A OB1
相关产品推荐
相关产品推荐

