useContext和useReducer挂钩不起作用。错误:无法读取未定义的属性“状态”

时间:2019-07-21 03:15:44

标签: reactjs typescript react-native react-hooks react-context

我正在尝试使用createContext,useReducer和useContext在React Native中实现Redux概念。以下是我的代码文件:

Store.tsx

4

App.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>
  );
}

我不确定为什么我无法在useContex中访问“状态”。我收到错误消息“ 无法读取未定义的属性'状态'” 请帮忙。如果您也可以给出详细的解释,那将非常有帮助。

1 个答案:

答案 0 :(得分:0)

您只能在上下文提供者的子组件中访问上下文的值。在这种情况下,您将在Store中调用呈现提供者的上方的useContext。在这些情况下,将提供传递给createContext的默认值。在这种情况下,createContext()没有给出默认值,因此未定义。因此,尝试破坏未定义的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
  }
});