Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 仅使用useEffect对自定义挂钩进行反应_Reactjs_Redux_React Hooks - Fatal编程技术网

Reactjs 仅使用useEffect对自定义挂钩进行反应

Reactjs 仅使用useEffect对自定义挂钩进行反应,reactjs,redux,react-hooks,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 'lodas

我创建了一个自定义挂钩,当存储中的某些值发生更改时,它使用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 ( ... )
}

这一切都像我期望的那样工作,但是像我那样调用和使用钩子可以吗?

您的自定义钩子也在使用
useSelector
useDispatch
useRef
。但是是的,我觉得没关系。看起来每次渲染都会调用它,但我想这就是你的目的。@DrewReese谢谢!我澄清说,我不仅在使用useEffect。