简体   繁体   中英

React Redux when the child component button is pressed how to have the websocket client send data if the websocket client is in the parent?

In my parent component I have

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

My child component has this button when clicked it runs this method:

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

My thought process was that to pass something from child to parent component - I will utilize the store. So whenever the button in a child component of parent component (which is a list) is clicked then the data that comes from child component will be accessible to the parent. The reason why I did this is because the websocket client is situated at the parent component.

The problem is that when the button in the child component is clicked once it runs the componentWillReceiveProps(nextProps) method in the parent component;

however, when I click it again it doesn't run. I understand that the payload doesn't change but gets set to the same thing again, so I thought when the dispatch action is called again after clicking on the button it will at least have the componentWillReceiveProps(nextProps) method in parent run again?

Is there a way to have to have it so that, when I click on a button of a child component - the websocket that is in my parent component send the data of the individual child component?

Essentially, I wanted to have the websocket client send messages to the server when the button in the child component is clicked

perhaps a different way to think about your question is to simply pass a function sendMessageToServer and data as props to the child component. as a functional component, it would look something like this:

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>
  );
}

in doing so, the function executes in the parent's scope whenever the button is clicked in the child. this can of course be written as a class component as well. for illustration purposes, i thought a functional component is easier to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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