Global state in React Native

前端 未结 6 1689
自闭症患者
自闭症患者 2020-12-06 10:03

I am developing a React Native application.

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 compone

相关标签:
6条回答
  • 2020-12-06 10:43

    I usually create a global.js containing:

    module.exports = {
       screen1: null,
    };
    

    And get the value of the state on the screen

    import GLOBAL from './global.js'
    
    constructor() {
    
        GLOBAL.screen1 = this;
    
    }
    

    Now you can use it anywhere like so:

    GLOBAL.screen1.setState({
        var: value
    });
    
    0 讨论(0)
  • 2020-12-06 10:45

    There are some alternatives to Redux in terms of state management. I would recommend you to look at Jumpsuit and Mobx. However do not expect them to be easier than Redux. State management is mostly a magical thing and most of the gizmo happens behind the scenes.

    But anyways if you feel that you need some global state management, it worths your time to master one of the solutions no matter Redux or Mobx or etc. I would not recommend using AsyncStorage or anything hacky for this purpose.

    0 讨论(0)
  • 2020-12-06 10:50

    If you are new to react (as me) and got confused by the first answer. First, use a component Class

    export default class App extends React.Component {
    
    constructor(props) {
      super(props);
      this.state = {
        walk: true
      };
      GLOBAL.screen1 = this;
    }
    
    render() {
      return (
        <NavigationContainer>
          <Stack.Navigator>
          {this.state.walk ? (
            <>
              <Stack.Screen name="WalkThrough" component={WalkThroughScreen} />
            </>
          ) : (
            <Stack.Screen name="Home" component={HomeScreen} />
          )}
        </Stack.Navigator>
        <StatusBar style="auto" />
      </NavigationContainer>
     )
    }
    

    Then you can do in any other component (My components are on /components, global is on root):

    import GLOBAL from '../global.js'
    
    GLOBAL.screen1.setState({walk:false})
    
    0 讨论(0)
  • 2020-12-06 10:52

    I usually do globals like this:

    I creat an globals.js

    module.exports = {
      USERNAME: '',
    };
    

    Something like that to store the username then you just need to import :

    GLOBAL = require('./globals');
    

    And if you wanna store the Data, lets say you want to save the username just do :

    var username = 'test';
    GLOBAL.USERNAME = username;
    

    And there you go , you just need to import GLOBAL on the pages you want and use it, just use if (GLOBAL.username == 'teste').

    0 讨论(0)
  • 2020-12-06 10:54

    Update since React 16.8.0 (February 6, 2019) introduce Hooks.

    it is not mandatory to use external library like Mobx or Redux. (Before Hook was introduce I used both of this state management solutions)

    you can create global state just with 10 line Source

    import React, {createContext, useContext, useReducer} from 'react';
    export const StateContext = createContext();
    export const StateProvider = ({reducer, initialState, children}) =>(
      <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
      </StateContext.Provider>
    );
    export const useStateValue = () => useContext(StateContext);
    

    extend your app with global state:

    import { StateProvider } from '../state';
    
    const App = () => {
      const initialState = {
        theme: { primary: 'green' }
      };
    
      const reducer = (state, action) => {
        switch (action.type) {
          case 'changeTheme':
            return {
              ...state,
              theme: action.newTheme
            };
    
          default:
            return state;
        }
      };
    
    
      return (
        <StateProvider initialState={initialState} reducer={reducer}>
            // App content ...
        </StateProvider>
      );
    }
    

    For details explanation I recommend to read this wonderful medium

    0 讨论(0)
  • 2020-12-06 10:54

    There appears to be a GLOBAL object. If set in app.js as GLOBAL.user = user, it appears to be available in other components, such as the drawer navigation.

    0 讨论(0)
提交回复
热议问题