Ama*_*rma 2 typescript reactjs react-native react-context react-hooks
我正在尝试使用 createContext、useReducer 和 useContext 在 React Native 中实现 Redux 概念。下面是我的代码文件:
商店.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>
);
}
Run Code Online (Sandbox Code Playgroud)
应用程序.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
}
});
Run Code Online (Sandbox Code Playgroud)
我不确定为什么我无法访问 useContex 中的“状态”。我收到错误“无法读取未定义的属性‘状态’ ”请帮忙。如果您也能详细说明一些很好的解释,那将非常有帮助。
TLa*_*add 10
您只能访问上下文提供程序的子组件中的上下文值。在这种情况下,您在 Store 中调用上面呈现提供程序的 useContext。在这些情况下,会给出传递给 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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9592 次 |
| 最近记录: |