sam*_*uel 0 components state reactjs react-native expo
我有一个 Fire 类,uid如果用户未连接,则返回未定义,如果用户已连接,则返回字符串(他的 uid)。
有时我的渲染取决于此。
例如 :
const [auth, setAuth] = useState<undefined|string>(Fire.shared.uid);
[...]
<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>
Run Code Online (Sandbox Code Playgroud)
我们可以想象用户没有连接,因此文本将是not authentificated。现在他将在其他页面登录或注册,因此Fire类中的 uid 变量将发生变化。那么我应该如何改变状态值呢?
没有 useState 全局或类似的东西吗?
谢谢。
你应该使用上下文:
页面上下文.js
export const PageContext= React.createContext();
Run Code Online (Sandbox Code Playgroud)
应用程序.js
const App = () => {
const [auth, setAuth] = useState<undefined|string>(undefined);
return(
<PageContext.Provider value={[auth, setAuth]}>
<NavigationContainer> // your routes
</PageContext.Provider>)
Run Code Online (Sandbox Code Playgroud)
其他屏幕.js
function OtherScreen() {
const [auth] = useContext(PageContext);
return (<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>)
}
Run Code Online (Sandbox Code Playgroud)
Sign.js
function Sign() {
const [auth, setAuth] = useContext(PageContext);
return (<Button onPress={()=>setAuth("myUid)} />)
}
Run Code Online (Sandbox Code Playgroud)