Хуки useContext и useReducer не работают. Ошибка: не удается прочитать состояние свойства undefined

Я пытаюсь реализовать концепцию Redux в React Native, используя createContext, useReducer и useContext. Ниже мои файлы кода:

Store.tsx

import React, { useReducer, createContext } from "react";
import { View, Text, StyleSheet, Button } from "react-native";

export const myContext = createContext();

export default function Store(props) {
  const counter = 0;
  const [state, dispatch] = useReducer((state, action) => {
    return state + action;
  }, counter);
  return (
    <myContext.Provider value={{ state, dispatch }}>
      {props.children}
    </myContext.Provider>
  );
}

App.tsx

import React, { useState, useContext, useEffect, createContext } from            "react";
import { View, Text, StyleSheet, Button } from "react-native";
import Store, { myContext } from "./components/Store";

export default function App(): JSX.Element {
  const { state, dispatch } = useContext(myContext);

  return (
    <View style={styles.wrapper}>
      <Text>HEY</Text>
      <Store>
        <Text>Counter: {state}</Text>
        <Button title="Incr" onPress={() => dispatch(1)} />
        <Button title="Decr" onPress={() => dispatch(-1)} />
      </Store>
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    marginTop: 100
  }
});

Я не уверен, почему я не могу получить доступ к «State» в useContex. Я получаю сообщение об ошибке «Не удается прочитать состояние свойства undefined». Любая помощь, пожалуйста. Было бы очень полезно, если бы вы могли дать хорошее объяснение с деталями.


person AmanDeepSharma    schedule 21.07.2019    source источник


Ответы (1)


Вы можете получить доступ только к значению контекста в дочернем компоненте поставщика контекста. В этом случае вы вызываете useContext выше, где отображается Provider, в Store. В этих случаях передается значение по умолчанию для createContext. В этом случае createContext(), значение по умолчанию не задано, поэтому оно не определено. Следовательно, попытка деструктуризации undefined const { state, dispatch } = useContext(myContext); приводит к ошибке, которую вы видите.

Просто добавление дополнительного дочернего компонента должно заставить его работать. Что-то вроде:

import React, { useState, useContext, useEffect, createContext } from            "react";
import { View, Text, StyleSheet, Button } from "react-native";
import Store, { myContext } from "./components/Store";

export default function AppWrapper(): JSX.Element {
  // Store, renders the provider, so the context will be accessible from App.
  return (
    <Store>
      <App />
    </Store>
  )
}

function App(): JSX.Element {
  const { state, dispatch } = useContext(myContext);

  return (
    <View style={styles.wrapper}>
      <Text>HEY</Text>
      <Text>Counter: {state}</Text>
      <Button title="Incr" onPress={() => dispatch(1)} />
      <Button title="Decr" onPress={() => dispatch(-1)} />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    marginTop: 100
  }
});
person TLadd    schedule 21.07.2019