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

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

问题描述

在与Redux,flux和其他pub / sub方法挣扎太多之后,我最终得到了以下技术。我不知道这是否会造成一些重大损失或瑕疵,所以在这里张贴以获得有经验的程序员关于其利弊的一些启示。

After struggling too much with Redux, flux and other pub/sub methods i ended up with the following technique. I do not know if that can cause some big damage or flaws so posting it here to get some light from the experienced programmers about its pros and cons.

var thisManager = function(){

    var _Manager = [];
    return{
        getThis : function(key){
            return  _Manager[key];
        },
        setThis : function(obj){            
            _Manager[obj.key] = obj.value;
        }
    }
};
var _thisManager = new thisManager();

// React Component
class Header extends Component{
   constructor(){
      super();
      _thisManager.setThis({ key: "Header", value:this}
   }
    someFunction(data){
        // call this.setState here with new data. 
   }
   render(){
      return <div />
   }
}

// Then from any other component living far somewhere you can pass the data to the render function and it works out of the box. 
i.e. 

class Footer extends Component{
  _click(e){
     let Header = _thisManager.getThis('Header');
     Header.somefunction(" Wow some new data from footer event ");
  }
 render(){
      return(
      <div>
          <button onClick={this._click.bind(this)}> send data to header and call its render </button>
      </div>


      );
  }
}



<我正在我的应用程序中发送json作为数据,它完美呈现所需的组件,我可以在没有任何发布的情况下调用渲染/ sub或deep传递props以调用父方法,更改this.setState以重新渲染。

I am sending json as a data in my application and it perfectly renders the desired components and i can invoke the render without any pub/sub or deep passing down the props to invoke a parent method with a changing this.setState to cause re-render.

到目前为止,该应用程序运行良好,我也非常喜欢它的简单性。请注意这项技巧的利弊

So far the application works fine and i am also loving its simplicity too. Kindly throw light on this technique pros and cons

问候

编辑:

调用渲染是不好的,所以我将其更改为另一种方法,以获得更多这种设置的优缺点。

It is bad to call render so i changed it to another method to get more pros and cons of this setup.

推荐答案

此设置有两个主要问题:

1。您永远不应该直接调用反应生命周期方法

2。后门组件是一个坏主意,它会破坏反应的可维护性

Two main concerns with this setup:
1. You should never call react lifecycle methods directly
2. Backdoors into components are a bad idea, which destroy react's maintainability

广告1:
如果你调用 render()(或任何其他反应方法)直接,反应可能不会调用 componentDidMount(),componentDidUpdate()`和组件树中的其他生命周期方法。

Ad 1: If you invoke render() (or any other react method) directly, react probably does not call componentDidMount(), componentDidUpdate()` and other lifecycle methods in the component tree.

危险是:


  • 许多设计react组件严重依赖于被触发的生命周期方法: getInitialState() componentWillReceiveProps() shouldComponentUpdate() componentDidMount()等等。如果你打电话给 render()直接,许多组件可能会破坏或显示出奇怪的行为。

  • 你冒着破坏反应差异引擎的风险:通过生命周期管理,react保持DOM的虚拟副本(内部存储器。为了正常工作,这个副本的完整性对于做出反应至关重要。

  • Many designs with react component rely heavily on the lifecycle methods being fired: getInitialState(), componentWillReceiveProps(), shouldComponentUpdate(), componentDidMount(), etc etc. If you call render() directly, many components will likely break or show strange behaviour.
  • You run the risk of breaking react's difference engine: through life-cycle management, react keeps a virtual copy of DOM in its (internal) memory. To work correctly, the integrity of this copy if vital to react's working.

更好(但仍违反我的第二点):

Better would be (but still in violation of my second point):


  • 在组件中包含一个不同的方法。

  • 如果你想要一个 setState()重新渲染。

  • 并从外部调用该方法。

  • Include a different method inside the component.
  • Which has a setState() if you want to re-render.
  • And call that method from the outside.

Ad 2。
对已安装组件的直接引用(与thisManager一样)存在一些额外的风险。 React的设计和限制有一个原因:用道具和状态维护单向流和组件层次结构,使事情易于维护。

Ad 2. A direct reference to a mounted component (as your thisManager does) has some additional risks. React's designs and limitations are there for a reason: to maintain unidirectional flow and component hierarchy with props and state, to make things easy to maintain.

如果你打破这种模式 - 通过在组件中构建一个后门,允许操纵状态 - 你打破了这个反应的设计原则。这是一个快速的快捷方式,但是当你的应用程序增长时肯定会带来巨大的痛苦和挫折感。

If you break this pattern - by building a backdoor into a component, which allows manipulation of state - you break this design principle of react. It is a quick shortcut, but is sure to cause great pain and frustation when your app grows.

据我所知,此规则唯一可接受的例外是:

As far as I know, the only acceptable exceptions to this rule are:


  • 响应ajax调用结果的组件内部的方法,以更新状态(例如,从服务器获取数据后)

  • 组件内部处理来自其直接后代子组件的触发器的方法(例如,在单击子按钮后在窗体上运行验证)

因此,如果您想将其用于此目的,那么您应该没问题。
警告提示:标准反应方法保护对组件的随机访问,因为调用组件或方法需要具有对组件的引用。在这两个示例中,这样的引用都可用。

在您的设置中,任何外部代码都可以在表中查找ref到header,并调用更新状态的方法。
使用这种间接引用,并且无法确定哪个源实际上调用了您的组件,您的代码可能变得更难以调试/维护。

So if you want to use it for that purpose, then you should be fine. Word of warning: the standard react approach guards random access to components, because the invoking component or method needs to have a reference to the component. In both examples such a reference is available.
In your setup, ANY outside piece of code could lookup the ref to the "header" in your table, and call the method which updates state. With such indirect reference, and no way of telling which source actually called your component, your code is likely to become much harder to debug/ maintain.

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

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