首页 > 解决方案 > 按下子组件按钮时反应 Redux 如果 websocket 客户端在父级中,如何让 websocket 客户端发送数据?

问题描述

在我的父组件中,我有

componentWillReceiveProps(nextProps) {
 if(nextProps.message) {
    websocket.send(JSON.stringfy(nextProps.message));
  }
}

我的子组件在单击时具有此按钮,它运行此方法:

onClickButton = () => {
  // My action dispatcher for reducer
  this.props.sendMessage(this.props.data);
}

我的思考过程是将某些东西从子组件传递给父组件 - 我将利用商店。因此,每当单击父组件(即列表)的子组件中的按钮时,父组件就可以访问来自子组件的数据。我这样做的原因是 websocket 客户端位于父组件中。

问题是,当子组件中的按钮一旦在父组件中运行 componentWillReceiveProps(nextProps) 方法时被点击;

但是,当我再次单击它时,它不会运行。我知道有效负载不会改变,但会再次设置为相同的东西,所以我认为在单击按钮后再次调用调度操作时,它至少会让父级中的 componentWillReceiveProps(nextProps) 方法再次运行?

有没有办法让它,当我点击一个子组件的按钮时 - 我的父组件中的 websocket 发送单个子组件的数据?

本质上,我想让 websocket 客户端在单击子组件中的按钮时向服务器发送消息

标签: javascriptreactjsreact-nativeredux

解决方案


也许考虑您的问题的另一种方式是简单地将函数sendMessageToServerdata作为道具传递给子组件。作为一个功能组件,它看起来像这样:

export default function Parent() {
  // this child component doesnt have to be here, can be imported or declared outside of this Parent functional component. it's here for demo purposes.
  const Child = ({ data, sendMessageToServer }) => {
    return <button onClick={() => sendMessageToServer(data)}>Send Data</button>;
  };
  const websocket = {
    send(msg) {
      console.log(msg);
    }
  };
  const sendMessageToServer = msg => {
    websocket.send(JSON.stringify(msg));
  };
  const data = { msg: "message from parent" };
  return (
    <div className="App">
      <Child {...{ data, sendMessageToServer }} />
    </div>
  );
}

这样做时,只要在子级中单击按钮,该函数就会在父级范围内执行。这当然也可以写成一个类组件。出于说明目的,我认为功能组件更容易理解。


推荐阅读