简体   繁体   English

在反应组件之外使用反应组件的方法

[英]Using methods of react components outside of react components

I'm making a chat app and want to keep its parts separate. 我正在制作一个聊天应用程序,并希望将其各个部分分开。

For example, I have part of code where communication logic is described. 例如,我有一部分代码描述了通信逻辑。 So when somebody receives a message addMessage function can be used to pass it to react component: 因此,当有人收到消息时,可以使用addMessage函数将其传递给组件进行响应:

import { addMessage } from './components/App.Chat.MessageField'

rtc.on('data', (data) => {
  /.../
  addMessage(message);
});

And addMessaget function is binded method of react component: addMessaget函数是react组件的绑定方法:

export var addMessage;

export default class MessageField extends Component {

  constructor() {
    /.../
    addMessage = this.addMessage.bind(this);
  }

  render() {
    /.../
  }

  addMessage(message) {
    /.../
    this.setState(/.../);
  }

}

So far, everything worked well. 到目前为止,一切正常。 But I doubt that's good solution. 但是我怀疑这是个好解决方案。 Can it cause some problems or is there any better ways to do it? 它会引起一些问题还是有更好的方法来解决?

This will lead to bugs. 这将导致错误。 If you invoke setState on an unmounted component React will throw an error. 如果在未安装的组件上调用setState ,React将引发错误。 In your example it means that if you are not in the case where MessageField is never unmounted then at some point addMessage will throw. 在您的示例中,这意味着如果您不处于永不挂载MessageField的情况,那么有时将抛出addMessage Of course your app should not rely on any of your component never unmounting as it is a core part of the react's semantics. 当然,您的应用程序不应该依赖于任何永不卸载的组件,因为它是React语义的核心部分。

A better way to do this could be to use redux and have the "add message" behaviour refactored around using redux state and actions. 更好的方法是使用redux并使用redux状态和操作重构“添加消息”行为。 Your rpc.on snippet could be also put inside its own middleware. 您的rpc.on代码段也可以放入其自己的中间件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM