我试图通过数据从redux存储到其他组件,但错误来尝试了很多事情。
app.js的代码如下所示, Package 在provider中
import React from 'react';
import Babe from './Babe';
import type { PropsWithChildren } from 'react';
import Test from './navigate/Test';
import Hot from './navigate/Hot';
import Coffee from './navigate/Coffee';
import Tea from './navigate/Tea';
import FullCourse from './navigate/FullCourse';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import FullCourse2 from './navigate/FullCourse2';
import { Provider } from 'react-redux';
import store from './src/app/store';
import { useSelector } from "react-redux";
import { showData } from './src/features/showslice'
const Stack = createStackNavigator();
上面的部分有所有必要的导入,下面的部分是问题是在使用useSelector
钩子。
const App = () => {
const data = useSelector((c) => {
return console.log(c)
})
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="In-Flight Services" component={Babe} />
<Stack.Screen name="Cold Water" component={Test} />
<Stack.Screen name="Hot Water" component={Hot} />
<Stack.Screen name="Tea" component={Tea} />
<Stack.Screen name="Coffee" component={Coffee} />
<Stack.Screen name="Meal" component={FullCourse} />
<Stack.Screen name="Meal2" component={FullCourse2} />
</Stack.Navigator>
</NavigationContainer>
</Provider>
)
}
export default App;
切片代码如下,我试图将值5即state.value
访问到app.js中。
import { createSlice } from '@reduxjs/toolkit'
// const initialState = { value: 0 }
export const showslice = createSlice({
name: 'showData',
initialState: { value: 3 },
reducers: {
addData: () => { },
showData: (state, action) => {
return state.value = 5
}
}
})
export const { addData, showData } = showslice.actions
export default showslice.reducer
// Action creators are generated for each case reducer function
// the showData in the store which is being assigned represents showslice.reducer
商店代码如下
// import { configureStore } from '@reduxjs/toolkit'
import { configureStore } from '@reduxjs/toolkit'
import showData from '../features/showslice'
const store = configureStore({
reducer: {
show: showData
},
})
export default store
多次检查导入是否正确。
我希望useSelector
的值存储在const data
中以便显示它,但在useSelector
行发生了错误。
1条答案
按热度按时间anhgbhbe1#
App
组件是呈现Redux storeProvider
组件的组件,因此App
本身***不能通过useSelector
钩子***订阅store。如果App
需要订阅store,那么Provider
组件应该在ReactTree中移动到比App
组件更高的位置,试图访问它提供的上下文。示例:
Provider
为其子ReactTree提供Redux上下文。此外,切片归约器应该只改变状态***或***返回下一个状态值,但不能两者都是。
或