【问题标题】:How to use global variables in React Native?如何在 React Native 中使用全局变量?
【发布时间】:2016-02-23 12:26:13
【问题描述】:

在 React Native 中,我想在不同屏幕之间移动时使用全局变量

谁能帮我实现它?

【问题讨论】:

  • 非常糟糕的模式,但无论如何:您可以在 window 对象上设置属性,就像在一个组件中执行 window.myvar = 123 一样,然后在另一个组件中读取它,console.log(window.myvar); // 123

标签: react-native


【解决方案1】:

React Native 中的全局作用域是全局变量。比如global.foo = foo,那么你可以在任何地方使用global.foo。

但不要滥用它!在我看来,全局范围可以用来存储全局配置或类似的东西。在不同的视图之间共享变量,正如你的描述,你可以选择许多其他的解决方案(使用 redux,flux 或将它们存储在更高的组件中),全局范围不是一个好的选择。

定义全局变量的一个好习惯是使用 js 文件。例如 global.js

global.foo = foo;
global.bar = bar;

然后,确保在项目初始化时执行它。比如导入index.js中的文件:

import './global.js'
// other code

现在,您可以在任何地方使用全局变量,而无需在每个文件中导入 global.js。 尽量不要修改它们!

【讨论】:

  • 如果我想使用全局变量,比如 BASE_URL,我可以在 App.js 文件或索引文件中声明它吗?
  • "全局范围不是一个好的选择。" @germinate 我能问一下为什么会这样吗?
  • 保存重物(大约 0.5 MB)是个好主意吗?我想从 RealmJS 加载一些数据并在不同的屏幕中使用它们。加载数据大约需要 1.5 秒。
  • @barrylachapelle ... (1) 覆盖其他全局值。 (2) 很难检测到来自哪里。
  • @AmirShabani。你可以。但请确保,“它可以使用”。因为它是异步的。你可能会在声明之前读取数据......
【解决方案2】:

尝试在index.android.jsindex.ios.js中使用global.foo = bar,然后可以在其他文件js中调用。

【讨论】:

    【解决方案3】:

    您可以考虑利用 React 的 Context 功能。

    class NavigationContainer extends React.Component {
        constructor(props) {
            super(props);
            this.goTo = this.goTo.bind(this);
        }
        goTo(location) {
            ...
        }
        getChildContext() {
            // returns the context to pass to children
            return {
                goTo: this.goTo
            }
        }
        ...
    }
    
    // defines the context available to children
    NavigationContainer.childContextTypes = {
        goTo: PropTypes.func
    }
    
    class SomeViewContainer extends React.Component {
        render() {
            // grab the context provided by ancestors
            const {goTo} = this.context;
            return <button onClick={evt => goTo('somewhere')}>
                Hello
            </button>
        }
    }
    
    // Define the context we want from ancestors
    SomeViewContainer.contextTypes = {
        goTo: PropTypes.func
    }
    

    使用context,您可以通过组件树传递数据,而无需在每个级别手动向下传递道具。有一个 big warning 表示这是一个实验性功能,将来可能会中断,但我想这个功能会出现,因为像 Redux 这样的大多数流行框架都广泛使用context

    使用context vs. 的主要优势全局变量context 被“限定”到一个子树(这意味着您可以为不同的子树定义不同的范围)。

    请注意,您不应通过context 传递模型数据,因为context 的更改不会触发 React 的组件渲染周期。但是,我确实发现它在某些用例中很有用,尤其是在实现您自己的自定义框架或工作流时。

    【讨论】:

      【解决方案4】:

      你可以使用 global 关键字来解决这个问题。

      假设您要将一个名为 isFromManageUserAccount 的变量声明为全局变量,您可以使用以下代码。

      global.isFromManageUserAccount=false;
      

      这样声明后,您可以在应用程序的任何位置使用此变量。

      【讨论】:

        【解决方案5】:

        设置助焊剂容器

        简单例子

        import alt from './../../alt.js';
        
            class PostActions {
                constructor(){
                this.generateActions('setMessages');
                }
        
                setMessages(indexArray){
                    this.actions.setMessages(indexArray);
                }
            }
        
        
        export default alt.createActions(PostActions);
        

        商店是这样的

        class PostStore{
        
            constructor(){
        
               this.messages = [];
        
               this.bindActions(MessageActions);
            }
        
        
        
        
            setMessages(messages){
                this.messages = messages;
            }
        }
        
        export default alt.createStore(PostStore);
        

        那么每个监听 store 的组件都可以共享这个变量 在你的构造函数中是你应该抓住它的地方

        constructor(props){
            super(props);
        
           //here is your data you get from the store, do what you want with it 
            var messageStore = MessageStore.getState();
        
        }
        
        
            componentDidMount() {
              MessageStore.listen(this.onMessageChange.bind(this));
            }
        
            componentWillUnmount() {
              MessageStore.unlisten(this.onMessageChange.bind(this));
            }
        
            onMessageChange(state){ 
                //if the data ever changes each component listining will be notified and can do the proper processing. 
           }
        

        这样,您可以跨应用共享数据,而无需每个组件相互通信。

        【讨论】:

          【解决方案6】:

          如果你只是想将一些数据从一个屏幕传递到下一个屏幕,你可以使用navigation.navigate 方法传递它们,如下所示:

          &lt;Button onPress={()=&gt; {this.props.navigation.navigate('NextScreen',{foo:bar)} /&gt;

          在“NextScreen”中,您可以使用navigation.getParam() 方法访问它们:

          let foo=this.props.navigation.getParam(foo);

          但如果要传递的变量超过几个,它可能会变得非常“混乱”..

          【讨论】:

            【解决方案7】:

            例如,您应该在 React Native 中执行此操作的方式(据我了解)是将“全局”变量保存在 index.js 中。然后你可以从那里使用道具传递它。

            例子:

                class MainComponent extends Component {
            
                    componentDidMount() {
                        //Define some variable in your component
                        this.variable = "What's up, I'm a variable";
                    }
                    ...
                    render () {
                        <Navigator
                            renderScene={(() => {
                                return(
                                    <SceneComponent
                                            //Pass the variable you want to be global through here
                                            myPassedVariable={this.variable}/>
                                );
                            })}/>
                    }
                }
            
            
                class SceneComponent extends Component {
            
                    render() {
                        return(
                            <Text>{this.props.myPassedVariable}</Text>
                        );
                    }
            
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-02-03
              • 1970-01-01
              • 2020-11-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-06-11
              相关资源
              最近更新 更多