【发布时间】:2019-11-29 11:42:55
【问题描述】:
我正在尝试使用 createContext、useReducer 和 useContext 在 React Native 中实现 Redux 概念。以下是我的代码文件:
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
}
});
我不确定为什么我无法在 useContex 中访问“状态”。我收到错误“无法读取未定义的属性“状态”” 请提供任何帮助。如果您也可以提供一些详细的解释,那将非常有帮助。
【问题讨论】:
标签: reactjs typescript react-native react-hooks react-context