【问题标题】:ReactJS + flux - how to handle session-like parameters (pseudoauthorization)ReactJS + Flux - 如何处理类似会话的参数(伪授权)
【发布时间】:2015-07-10 17:19:51
【问题描述】:

这是用例:

我的 reactjs 应用程序中有 2 个组件。两个组件都通过 websocket 接收来自远程服务器的数据。我不希望我的组件和存储知道数据源 - 所有 websocket 逻辑都驻留在 ActionCrators 和我称之为 SocketListeners 的东西中。

以下是此类监听器的示例:

var listen = function (socket) {
  socket
    .on(Messages.LIGHTS_CHANGED, function (newConfiguration) {

      AppDispatcher.dispatch({
        type: LightActionTypes.SUBSTITUTE_LIGHT_CONFIGURATION,
        payload: newConfiguration
      });

    })      
};

module.exports = {
  listen: listen
};

由于它是一个 websocket,我需要知道远程 url。 我想请我的用户在我的主页上提供这个 URL - 在此之前,我的组件(实际上 - 路由)不应该可用,并且用户应该被重定向到他能够指定这个 URL 的页面。

所以我需要一些看起来像登录流程的东西——但这里的关键属性不是登录名和密码,而是远程 url。

您将如何管理这种类似会话的状态?

我尝试过这样的事情:

在我的表单式主页视图中,我有一个功能:

handleConnectionConfirmed: function(event) {
    event.preventDefault();
    ActionCreator.saveRemoteUrl(
      this.state.remoteUrl
    );
  },

导致我的 ConfigurationStore 更新:

var _lightsUrl = '';
var _temperatureUrl = '';

var ConfigurationStore = {
  lightsSocketEndpoint: function () {
    return _lightsUrl;
  },

  temperatureSocketEndpoint: function () {
    return _temperatureUrl;
  }

};

然后我的两个组件都有:

componentWillMount: function () {
    ActionCreator.init();
  },

初始化函数:

init: function () {
    _socket = WebSocketFactory.lightsWebSocket();
    SocketListener.listen(_socket);
  },

最后一个sn-p:

lightsWebSocket: function () {
    return io.connect(
      ConfigurationStore.lightsSocketEndpoint()
    )
  },

问题是:只要我刷新任何页面,我的 ConfigurationStore 就会被清除。

如何在不使用外部存储的情况下以某种方式使其持久化?

另外,您知道如何配置 react-router,以便在未指定远程 url 并且用户尝试打开其中一个组件所在的站点时,它可以将我重定向到“登录”页面?

【问题讨论】:

    标签: reactjs flux react-router


    【解决方案1】:

    使用LocalStorageSessionStorage。例如:

    在你商店的构造函数中做:

    _lightsUrl = localStorage.getItem('lightsUrl') || '';
    

    并且在 store 的 dispatch handler 中:

    _lightsUrl = newLightsUrl;
    localStorage.setItem('newLightsUrl');
    

    这是一个很好的教程,它以这种方式进行身份验证(不要介意“Rails”部分):http://fancypixel.github.io/blog/2015/01/29/react-plus-flux-backed-by-rails-api-part-2/

    【讨论】:

    • 我认为使用 localStorage/sessionStore 更干净。您不需要额外的库,而且您不需要在每次请求时都将此 url 发送到服务器(这发生在 cookie 中)。除非你必须支持 IE8,否则在这种情况下:使用 cookie 并......祝你好运。
    猜你喜欢
    • 2015-07-26
    • 1970-01-01
    • 2014-10-13
    • 2012-12-22
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多