Я пытаюсь реализовать концепцию 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». Любая помощь, пожалуйста. Было бы очень полезно, если бы вы могли дать хорошее объяснение с деталями.