React Native 中的全局状态 [英] Global state in 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屋!