Redux useSelector在子组件中不返回任何内容



我是React Native和Redux的新手,希望有人能帮我解决这个问题?我有一个父组件,它获取一些用户数据(他们的位置(并将其发送到redux存储:

父级

import { useDispatch } from 'react-redux'
import { setLocation } from './store/locationSlice'
const App = () => {
const dispatch = useDispatch()

const getLocation = () => {
const location = await fetchLoc()
dispatch(setLocation(location))
}

useEffect(() => {
getLocation()
},[])

}

我的子组件旨在使用useSelector钩子检索这些数据

import { useSelector } from 'react-redux'
const HomeScreen = () => {
const location = useSelector(state => state.location)

useEffect(() => {
if (location) {
getEntitiesBasedOnLocation(location)
}

},[location])
}

然而,在我的情况下,useSelector从不检索我在父级中发送的最新信息,位置返回未定义。我很确定这里有一个简单的疏忽,但我不知道这可能是什么。我的印象是useSelector订阅了状态更改,那么为什么我调度的导致状态更改的操作被忽略了呢?使用我的调试器,我可以看到我的状态肯定是用正确的数据更新的,但子组件不会接受这一点。。

这是我的位置切片:

import { createSlice } from '@reduxjs/toolkit'
const initialState = {
location: {
id: null,
name: null,
latitude: null,
longitude: null
}
}
const locationSlice = createSlice({
name: 'location',
initialState,
reducers: {
setLocation: (state, action) => {
const { id, name, latitude, longitude } = action.payload
state.location = { id, name, latitude, longitude }
}
}
})
export const { setLocation } = locationSlice.actions
export default locationSlice.reducer

UPDATE通过将App.js组件封装在Provider组件中来配置存储,存储作为其道具传递,如下所示:

Root.js

import { configureStore } from '@reduxjs/toolkit'
import { Provider } from 'react-redux'
import locationReducer from './src/store/locationSlice'
import App from './src/App'
const Root = () => {
const store = configureStore({ reducer: locationReducer })
return (
<Provider store={store)>
<App />
</Provider>
)
}

问题出在选择器中。您已经创建了一个名为"location"的切片,在该切片中,您的状态为{ location: {...}}。因此,从选择器(它访问全局状态,而不仅仅是位置切片(的角度来看,数据的路径将是state.location.location。但是您的选择器正在尝试读取只有location道具的state.location。你试图读出的任何其他内容都是未定义的。

从切片配置导出自定义选择函数是很常见的。请记住,选择器必须精确地获取要在组件树中共享的数据(在本例中为locationSlice.state.location(。这不是强制性的,只是为了促进发展。

// locationSlice 
import { createSlice } from '@reduxjs/toolkit'
//...
export const { setLocation } = locationSlice.actions
export const selectLocation = (state) => state.location.location
export default locationSlice.reducer
// Child
import { useSelector } from 'react-redux'
import {selectLocation} from './src/store/locationSlice'
const HomeScreen = () => {
const location = useSelector(selectLocation)

//...
}

我的解决方法是将父组件中的getLocation()函数移动到子组件。useSelector现在获得了预期的状态。不过,我觉得这种解决方案违背了全局状态访问的目标,我可能只使用本地状态,而不是Redux。

最新更新