从外部访问React状态 [英] Accessing React state from outside

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

问题描述

我想使用React.js制作一个应用程序.我希望可以轻松地从外部对其进行自定义(例如,通过编写用户脚本).我尝试使用的想法是在根元素状态下创建一些特殊属性(例如sidebarItemsplaylistCreatedHooks),以便插件开发人员可以在此处添加一些内容.我的问题是:这是否是一个好方法,是否有Right Way™来实现与我的目标相似的目标,最后,附加组件开发人员将如何使用这些道具?

I want to make an app using React.js. I want it to be easily customizable from the outside world (e. g. by writing userscripts). The idea I attempted to use is to make some special properties in the root element state (like sidebarItems or playlistCreatedHooks) so addon developers could add something there. My questions are: is this a good way to do so, is there the Right Way™ to achieve something similar to my goal and, finally, how will addon developers access these props?

推荐答案

一个选项是可观察的.基本上,这是一个您可以监听更改并创建更改的对象.您还可以在data.playlists上发出其他事件,例如'add'事件,以创建您要提供的api.

One option is observables. Basically it's an object you can listen to changes on, and create a change on. You could also emit other events like an 'add' event on data.playlists to create the api you want to provide.

// data.js
var data = {
  sidebarItems: Observable([]),
  playlists: Observable([])
};

// app.js
var App = React.createComponent({
  mixins: [data.sidebarItems.mixin("sidebar")],
  render: function(){
    return this.state.sidebar.map(renderSidebarItem);
  }
});

/// userscript.js

// causes the view to update
data.sidebarItems.set(somethingElse); 

// run when someone does data.playlists.set(...)
data.playlists.on('change', function(playlists){

});

// an event you could choose to emit with data.playlists.emit('add', newPlaylist)
data.playlists.on('add', function(newPlaylist){

});

这是上面使用的Observable的示例(未经测试)实现,带有用于生成react组件mixin的额外功能.

Here's an example (untested) implementation of Observable used above, with an extra function for generating the react component mixin.

var events = require('events'); // or some other way of getting it
var Observable = function(initialValue){
  var self = new events.EventEmitter();
  var value = initialValue;

  self.get = function(){ return value };
  self.set = function(updated){
    value = updated;
    self.emit('change', updated);
  };
  self.mixin = function(key){
    var cbName = Math.random().toString();
    var mixin = {
      getInitialState: function(){ var o = {}; o[key] = value; return o },
      componentDidMount: function(){
        self.on('change', this[cbName]);
      },
      componentWillUnmount: function(){
        self.removeListener('change', this[cbName]);
      }
    }
    mixin[cbName] = function(){
      var o = {}; o[key] = value; this.setState(o);
    };
    return mixin;
  }

  return self;
}

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

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