【发布时间】:2022-11-29 07:20:20
【问题描述】:
我使用 react-query 提取数据,由于稍后要进行一些表单编辑,因此需要将其存储在状态中。
在表单编辑之前,它运行良好:
import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
const ProfilePage = ({ id }) => {
const {data, loading, error} = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
const { participant } =data;
return (
<div>
<ProfileGeneral participant={participant} />
</div>
但是在尝试将它添加到状态之后,我不断收到一条错误消息,表明它在没有准备好数据的情况下呈现。
import { useQuery } from '@apollo/client';
import { SINGLE_PARTICIPANT_QUERY } from 'queries/participantQueries';
import { ProfileGeneral } from './ProfileGeneral';
import { useEffect, useState } from 'react';
const ProfilePage = ({ id }) => {
const [participant, setParticipant] = useState(null);
const { data, loading, error } = useQuery(SINGLE_PARTICIPANT_QUERY, {
variables: {
id
}
});
useEffect(() => {
if (data && data.participant) {
setParticipant(data.participant);
}
}, [data, participant]);
if (loading) {
return <div>Loading</div>;
}
if (error) {
return (
<div>
{error.message} />
</div>
);
}
return (
<div>
<ProfileGeneral participant={participant} />
</div>
我回来了:
Server Error
TypeError: Cannot read properties of null (reading 'firstName')
This error happened while generating the page. Any console logs will be displayed in the terminal window.
我知道我需要让它等待或在它从查询中获得数据后立即重新呈现,但我不确定如何阻止它。
感谢您的观看!
【问题讨论】:
标签: reactjs react-hooks react-query