简体   繁体   中英

Pass props down to scenes and modify

Building an app using React Native and the individual scenes are working great, really happy with it.

However now I'm looking at introducing some "global" state, so for instance to check if a user has an active session and if so add their data to some state which is shared (or passed) to the rest of the app.

I'm just not 100% where to put this code and where I'd store this data so the individual scenes can access (and also just as importantly - modify) this data?

I've had a stab at adding a prop to the <Navigator /> , like so:

<Navigator user={this.getUser()} />

Which is then passed as a prop to <SomeScene navigator={navigator} /> but this doesn't feel right, and I can't figure out how to then modify a prop of navigator (say a user property changes) then have these changes filter back up to the main <Navigator /> .

From searching around I've seen Flux and React Router mentioned, but can't find an example of what I'm trying to do so was hoping someone could point me in the right direction.

Thanks in advance.

This can be achieve using Flux , let me explain me with Flux, Flux is pattern which have Store and you can use the Store to store the Variable value here I am cover your example you want to store user information and want to access on each and every component for that your store contains two method one is for set User information and second one is for get the user information.

First you have to install the two module for this using below mentioned command

npm install events underscore --save

var EventEmitter = require('events').EventEmitter;
var _ = require('underscore');

var _user;

// Extend UserStore with EventEmitter to add eventing capabilities
var UserStore = _.extend({}, EventEmitter.prototype, {


    getUserInfo: function() {
        return _user;
    },
    setUserInfo: function(user) {
        _user=user;
    }
});
module.exports=UserStore;

now you can use it this Store from any of your component like

var UserStore=require('./UserStore');

and set and get the userinfor from anywhere in your application like to set

UserStore.setUserInfo(user);
var user=UserStore.getUserInfo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM