仅使用useEffect反应自定义钩子

时间:2020-01-19 03:08:48

标签: reactjs redux react-hooks

我创建了一个自定义钩子,当存储中的某些值发生更改时,该钩子使用useEffect来更新redux存储:

import { useRef, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { index } from '../actions'
import { createSelector } from 'reselect'
import { omit } from 'lodash'

const selectPerformanceSearch = createSelector(
  state => omit(state.eventSearch, ['results', 'isFetching']),
  items => items
)

export default function useEventSearch() {
  const state = useSelector(selectEventSearch)
  const dispatch = useDispatch()
  const initialFetch = useRef(true)
  const { tags, near, filters } = state
  const { lng, lat, location } = near

  useEffect(() => {
    if (!initialFetch.current) {
      const data = { tags, lng, lat, filters }
      dispatch(index('/event/search', 'EVENT_SEARCH', data))
    }
  }, [tags, lng, lat, filters, dispatch])

  useEffect(() => {
    if (initialFetch.current && location) {
      initialFetch.current = false
      const data = { lng, lat }
      dispatch(index('/event/closest', 'EVENT_SEARCH', data))
    }
  }, [lng, lat, location, dispatch])
}

然后我有一个React组件,它像这样使用钩子:

import useEventSearch from '../../hooks/usePerformanceSearch'

const SearchBar = props => {
  // ...code

  usePerformanceSearch()

  /// ...other code
  return ( ... )
}

这一切都符合我的预期,但是可以像我以前那样使用钩子来调用吗?

0 个答案:

没有答案