【发布时间】:2021-07-17 15:38:11
【问题描述】:
所以我有这个代码
const [localState, setLocalState] = useState<StateType[]>([]);
const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, {
variables: {
id: client && client.id
},
skip: user.clients && user.clients.length === 0
});
useEffect(() => {
if (loading || !data) {
return undefined;
}
if (data && data.attribute) {
const sortedResult = data.attribute.sort((a, b) =>
a.updatedAt < b.updatedAt ? 1 : -1
);
setLocalState(sortedResult);
}
}, [data]);
问题是当 useQuery 返回 empty(undefined) 结果并且数据默认为 {attribute: []} useEffect 会一直被触发,但是当 useQuery 返回数据时(所以它不是默认的)useEffects 只被输入一次。这个问题的解决方案只是删除查询中的默认参数= {attribute: []},所以它看起来像这样:
const [localState, setLocalState] = useState<StateType[]>([]);
const { data, loading } = useQuery<DataType>(QUERY, {
variables: {
id: client && client.id
},
skip: user.clients && user.clients.length === 0
});
useEffect(() => {
if (loading || !data) {
return undefined;
}
if (data && data.attribute) {
const sortedResult = data.attribute.sort((a, b) =>
a.updatedAt < b.updatedAt ? 1 : -1
);
setLocalState(sortedResult);
}
}, [data]);
为什么 useQuery 中的默认参数会使 useEffect 被无限触发?
(要补充的重要说明 - 我试图删除排序功能,认为它会改变数据对象并导致重新输入,但它没有改变任何东西)
【问题讨论】:
标签: javascript reactjs typescript graphql react-hooks