Skip to content

Instantly share code, notes, and snippets.

@robotzhang
Last active January 19, 2020 14:48
Show Gist options
  • Save robotzhang/b6ce302e8d0fb2b3e96f0c648fd765da to your computer and use it in GitHub Desktop.
Save robotzhang/b6ce302e8d0fb2b3e96f0c648fd765da to your computer and use it in GitHub Desktop.
React Hook 相关的知识

需要阅读的文章: 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])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment