React钩子-如何按需调用useEffect?

时间:2019-04-24 08:59:19

标签: reactjs react-hooks

我正在用React钩子重写CRUD表。下面的自定义钩子useDataApi用于获取表的数据,监视url的变化-因此,当params发生变化时,它将被触发。但是我还需要在删除和编辑后获取最新数据。我该怎么办?

const useDataApi = (initialUrl, initialData) => {
  const [url, setUrl] = useState(initialUrl)

  const [state, dispatch] = useReducer(dataFetchReducer, { data: initialData, loading: true })

  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' })
      const result = await instance.get(url)
      dispatch({ type: 'FETCH_SUCCESS', payload: result.data })
    }

    fetchData()
  }, [url])

  const doFetch = url => {
    setUrl(url)
  }

  return { ...state, doFetch }
}

由于url在删除/编辑后保持不变,因此不会被触发。我想我可以有一个增量标志,并让useEffect对其进行监视。但这可能不是最佳做法吗?有没有更好的办法?

1 个答案:

答案 0 :(得分:1)

您需要做的就是从fetchData中取出useEffect方法,并在需要时调用它。另外,请确保将函数作为参数传递给依赖项数组。

const useDataApi = (initialUrl, initialData) => {
  const [url, setUrl] = useState(initialUrl)

  const [state, dispatch] = useReducer(dataFetchReducer, { data: initialData, loading: true })

  const fetchData = useCallback(async () => {
      dispatch({ type: 'FETCH_INIT' })
      const result = await instance.get(url)
      dispatch({ type: 'FETCH_SUCCESS', payload: result.data })
  }, [url]);

  useEffect(() => {
    fetchData()
  }, [url, fetchData]); // Pass fetchData as param to dependency array

  const doFetch = url => {
    setUrl(url)
  }

  return { ...state, doFetch, fetchData }
}