使用 useSelector() 时找不到 react-redux 上下文值

Could not find react-redux context value when using useSelector()

我是新手,正在尝试了解为什么会看到此错误:

Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

App.js

export default function App() {
  const selectedNumber = useSelector(selectChosenNumber) // This line causes the error

  function pickedNumberHandler() {
    console.log("called")
  }

  let screen = <StartGameScreen />;

  pickedNumberHandler()

  store.subscribe(pickedNumberHandler)

  return (
    <Provider store={store}>
      <LinearGradient colors={['#4e0329', '#ddb52f']} style={styles.rootScreen}>
        <ImageBackground
          source={require('./assets/images/background.png')}
          resizeMode="cover"
          style={styles.rootScreen}
          imageStyle={{opacity: 0.15}}
        >
          {screen}
        </ImageBackground>
      </LinearGradient>
    </Provider>
  );
}

const styles = StyleSheet.create({
  rootScreen: {
    flex: 1,
  }
})

chosenNumberReducer.ts

export const chosenNumberSlice = createSlice({
  name: "chosenNumber",
  initialState: {
    value: ""
  },
  reducers: {
    pickNumber: (state, action) => {
      state.value = action.payload
    }
  }
})

export const { pickNumber } = chosenNumberSlice.actions
export const selectChosenNumber = state => state.chosenNumber.value;
export default chosenNumberSlice.reducer

我正在尝试监听状态的变化,但似乎无法访问 app.js 中的值。

您需要将您的逻辑移到 App 之外。当它说 please ensure the component is wrapped in a <Provider> 时,这意味着您正在使用 useSelector 的组件需要在 <Provider> 下,在这种情况下意味着 App.js.

所以App.js应该只包含

export default function App() {
  return (
    <Provider store={store}>
      <NewComponent .../>
    </Provider>
  );
}

并且 NewComponent.js 应该包含其余的逻辑。