需要阅读的文章: https://overreacted.io/zh-hans/a-complete-guide-to-useeffect/ # 作者是 Dan Abramov,React 核心开发者 https://github.com/dt-fe/weekly/tree/master #
如果只是需要使用更改的数据:
const { loading, data, error } = useQuery(SOME_QUERY)
if (loading) return <Loader />
if (error) return <Error />
// safe to assume data now exist and you can use data.
const mutatedData = React.useMemo(() => {
// if you want to mutate the data for some reason
return data
}, [data])
return <YourComponent data={mutatedData} />
如果需要存储返回值,那么可以使用 useEffect:
const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])
React.useEffect(() => {
// do some checking here to ensure data exist
if (data) {
// mutate data if you need to
setState(data)
}
}, [data])
特别注意的是 hook order
问题:
const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])
if (loading) return <Loader />
if (error) return <Error />
// 此时会出现错误
React.useEffect(() => {
// do some checking here to ensure data exist
if (data) {
// mutate data if you need to
setState(data)
}
}, [data])