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

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

问题描述

我想使用 React.js 制作一个应用程序.我希望它可以从外部世界轻松定制(例如,通过编写用户脚本).我尝试使用的想法是在根元素状态中创建一些特殊属性(如 sidebarItemsplaylistCreatedHooks),以便插件开发人员可以在那里添加一些东西.我的问题是:这是一个很好的方法吗,是否有实现与我的目标类似的东西的正确方法™,最后,插件开发人员将如何访问这些道具?

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?

推荐答案

一个选项是 observables.基本上,它是一个可以监听更改并在其上创建更改的对象.您还可以在 data.playlists 上发出其他事件,例如添加"事件,以创建您想要提供的 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 的示例(未经测试)实现,带有用于生成反应组件混合的额外功能.

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天全站免登陆