React Native中的全局状态 [英] Global state in React Native

查看:152
本文介绍了React Native中的全局状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发React Native应用程序.

I am developing a React Native application.

我要保存登录用户的用户ID,然后检查用户是否在每个组件中都已登录.

I want to save the user id of the person who is logged in and then check if the user is logged in in every single component.

所以我要寻找的是诸如cookie,会话或全局状态之类的东西.

So what I am looking for is something like cookies, sessions or global states.

我已经读到我应该使用Redux,但这似乎太复杂了,很难与react-navigation一起使用.尽管我唯一想做的就是能够访问所有组件中的单个全局状态/变量,但这迫使我为几乎所有事物定义了动作和归约方法.

I have read that I should use Redux, but this seems to be overly complicated and it is very difficult to make it work with react-navigation. It forces me to define actions and reducers for almost everything although the only thing I want is to be able to access a single global state/variable in all components.

是否有其他选择,或者我是否应该真正重组整个应用程序以使用Redux?

Are there any alternatives or should I really re-structure my entire app to use Redux?

推荐答案

我通常创建一个包含以下内容的global.js:

I usually create a global.js containing:

module.exports = {
   screen1: null,
};

并在屏幕上获取状态值

import GLOBAL from './global.js'

constructor() {

    GLOBAL.screen1 = this;

}

现在您可以在任何地方使用它了,

Now you can use it anywhere like so:

GLOBAL.screen1.setState({
    var: value
});

这篇关于React Native中的全局状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆