【问题标题】:React Native, global useState?React Native,全局使用状态?
【发布时间】:2021-01-01 15:19:38
【问题描述】:

我有一个 Fire 类,如果用户未连接,uid 返回 undefined,如果用户已连接,则返回字符串(他的 uid)。

有时我的渲染依赖于此。

例如:

const [auth, setAuth] = useState<undefined|string>(Fire.shared.uid);

[...]

<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>

我们可以想象用户没有连接,所以文本将是not authentificated。 现在他将在另一个页面中登录或注册,因此Fire 类中的 uid 变量将发生变化。 那么我应该如何改变状态值呢?

没有useState global之类的吗?

谢谢。

【问题讨论】:

    标签: reactjs react-native components expo state


    【解决方案1】:

    你应该使用上下文:

    page-context.js

    export const PageContext= React.createContext();
    

    app.js

    const App = () => {
    const [auth, setAuth] = useState<undefined|string>(undefined);
    
    return(
        <PageContext.Provider value={[auth, setAuth]}>
           <NavigationContainer> // your routes
        </PageContext.Provider>)
    

    OtherScreen.js

    function OtherScreen() {
        const [auth] = useContext(PageContext);
        return (<Text>{(auth == undefined) ? "not authentificated" : "great")}</Text>)
    }
    

    Sign.js

     function Sign() {
        const [auth, setAuth] = useContext(PageContext);
        return (<Button onPress={()=>setAuth("myUid)} />)
     }
    

    【讨论】:

      【解决方案2】:

      你可以使用 react js context api 来拥有这个功能:https://reactjs.org/docs/context.html#updating-context-from-a-nested-component

      或者您可以使用 redux 或 mobx 等第三方库来拥有全局状态

      redux : https://redux.js.org/ 暴民:https://mobx.js.org/README.html

      【讨论】:

        猜你喜欢
        • 2017-10-28
        • 1970-01-01
        • 2021-11-23
        • 2019-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多