Reactjs 仅使用useEffect对自定义挂钩进行反应
我创建了一个自定义挂钩,当存储中的某些值发生更改时,它使用useEffect更新redux存储: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
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。