组件之间的通讯 [英] Communication between Components

查看:78
本文介绍了组件之间的通讯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的情况,我刚起步时就会做出反应/动摇,并开始尝试使用它.我的玩具项目是一个简单的图书馆应用程序.我当前的状态如下:

Here's my situation, I'm very new to react/flux, and just started to play around with it. My toy project is a simple library app. My current state is as follows:

  • 我有一个名为Login的组件.该组件仅负责存储当前已登录"的用户,以便能够处理库中后面的借入/返回"按钮.因此,用户输入了它的名称,该名称将立即保存到会话存储中.
  • 我的另一个组件称为库,它包含我应用程序的主要逻辑.

如果要更改当前用户,我将努力寻找如何重新渲染库组件的方法.自从我的第一个项目以来,我不想进行适当的身份验证或创建路由器.因此,我只创建了一个Login表单,每当用户输入他的名字并登录时,我就将库应用呈现到DOM上.

I'm struggling to find out how to re-render my library component if i change the current user. Since its my first project, I don't want to play around with proper authentication, or create a router. So I simply made a Login form and whenever the user input's his name, and logs in, i render the library app onto the DOM.

Login = React.createClass({

  _handleSubmit: function () {

    var inp = this.refs.login.getDOMNode();

    sessionStorage.setItem("username", inp.value);
    console.info('User Credentials saved to SessionStorage');
    inp.value = '';

    React.renderComponent(
      <Library />,
      document.querySelector('#content')
    );
  },

  render: function () {
    return (
      <div className="panel panel-default">
        blabla
                  <button className="btn btn-default" type="button" onClick={this._handleSubmit} >
                    Login
                  </button>
        blabla
      </div>
    );
  }
});

这很好,但是我认为这远非最佳方法.每当我再次登录时,react都会将新实例从库"组件重新呈现到DOM节点中.我根本不处理销毁问题,我认为这很不好:(我知道react不会追加,但是会擦除并填充到节点中,但是事件处理程序可能会保留下来,等等.

This works well, but i think it's far from an optimal approach. Whenever i Login again, react is re-rendering a new instance from the Library component into the DOM node. I'm not dealing with destructuring at all, and I think it's bad :( I know react will not append, but erase and fill into the node, but the event handlers will possibly remain etc.

那么对于我的情况,可能有什么好的解决方案?

So what could be a possible good solution for my situation?

我脑中有3种可能的解决方案

I have 3 possible solutions in my mind

  1. 如果我与其他用户重新登录以重新呈现自身,则我应该开发一个事件系统以能够通知Library组件,或者
  2. 我可以通过Login&建立亲子关系库,因此当我修改登录"组件的状态时,库"应用也会重新渲染.
  3. 调用将更新组件的动作
  4. 粘上电流

:)谢谢您的回答, 干杯

:) Thanks for any answer, Cheers

提示:

app.js

'use strict';
var React = require('react'),
    Login = require('./components/Login.jsx');

// Dev-tools
window.React = React;

React.renderComponent(
  Login(),
  document.querySelector('#login')
);

Login.jsx

提到的鞋帮

Library.jsx

/** @jsx React.DOM */
'use strict';
var React = require('react'),
    BookShelf = require('./BookShelf.jsx'),
    Store = require('../stores/Store'),
    Library;

/**
 * Gets state from Storage
 * @returns {{books: BookCollection, users: UserCollection, categories: CategoryCollection}}
 */
function getState() {
  var state = Store.getAll();
  return {
    books: state.books,
    users: state.users,
    categories: state.categories
  };
}

Library = React.createClass({
  getInitialState: function() {
    return getState();
  },
  componentDidMount: function() {
    Store.addChangeListener(this._onChange);
    Store.initialize();
  },
  componentWillUnmount: function() {
    Store.removeChangeListener(this._onChange);
  },
  _onChange: function() {
    this.setState(getState());
  },
  render: function() {
    return (
      <div>
        <BookShelf
          books={this.state.books}
          users={this.state.users}
          categories={this.state.categories}
        />
      </div>
    );
  }
});

module.exports = Library;

推荐答案

如果这是一个Flux应用程序,那么您想要获取所有应用程序逻辑和应用程序状态并将其移至一个商店(或多个商店)中.

If this is a Flux app, then you want to take all that application logic and application state and move it into a store (or multiple stores).

现在,对于与库有关的事情,看起来您正在这样做.我将重命名该商店LibraryStore.但是您可能需要AppStore或UserStore或SessionStore或具有与登录状态,当前用户和auth令牌相关的逻辑和数据的东西.

Right now, it looks like you're doing that just fine for things related to the library. I would rename that store LibraryStore. But you probably want an AppStore or a UserStore or a SessionStore or something that has the logic and data related to the login state, current user, and auth token.

因此,一旦用户登录,是的,您将要创建一个动作(选项3)以让您应用中的所有不同商店都知道您的用户已登录,但主要是通知AppStore.然后,您的顶级控制器视图可以收听AppStore并确定要显示的内容.如果您使用的是React的事件模型,则无需担心清理事件处理程序. Flux控制器视图不使用React模型,因此我们必须在卸载时清理它们.

So then once the user logs in, yes you would want to create an Action (option #3) to let all the different stores in you app know that your user has logged in, but primarily to inform the AppStore. Then your top-level controller-views can listen to AppStore and decide what to display. If you're using React's event model, you don't need to worry about cleaning up the event handlers. Flux controller-views don't use the React model, so we have to cleanup those on unmounting.

部分困难可能来自模拟异步过程.例如,身份验证将需要服务器调用,并且您的新操作将在该调用的成功/错误回调中创建.要针对localStorage对此进行模拟,您可以对存储进行同步查询,然后调用两个不同的操作之一以获取成功/失败.

Part of your difficulty may be coming from simulating processes that are async. Authentication, for example, will require a server call, and your new action would be created in the success/error callback to that call. To simulate this against localStorage, you might make a sync query of the storage and then call one of two different actions for success/failure.

这篇关于组件之间的通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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