在组件外部更新数组时,如何调用React重新渲染

时间:2018-09-03 11:11:21

标签: javascript reactjs

我建立了一个聊天应用程序,其中的聊天记录正在另一个文件中进行更新。聊天记录另存为数组。

现在您可以说我作弊了,每500毫秒更新一次组件。 我知道不鼓励使用this.forceupdate()。

 class MessageDisplay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {record :false};
  }

  componentDidMount() {
    send.sendMessageToServer("helloQuickreply");
  }

  componentDidUpdate() {
    const element = document.getElementById("scrollToMe");
    element.scrollIntoView({ behavior: "smooth" });
  }

  tick() {
    this.forceUpdate();
  }

  render() {
    setTimeout(() => {
      this.forceUpdate();
    }, 500);
    return (
      <div className="chatBox">
        <ui.showMessage />
      </div>
    );
  }
}

梦想是仅在用户发送或接收消息时强制进行更新。 那么如何在另一个文件中调用this.forceupdate()?

这是send.js 在这里叫它很漂亮

export function sendMessage(text) {
  fetch(url, {
    method: "POST", 
    async: true,
    body: JSON.stringify({ text:text}), 
  })
    .then(res => res.json())
    .catch(error => console.error("Error:", error))
    .then(response => {

      save_response_in_ChatArray()
      //Call Forceupdate somehow?
    });
}

数组显示如下: showMessage()也正在另一个文件中调用。

export function showMessage() {

  let listItems = messageList.map(d => (
    <div>
      <p className={d.senderId + "timestamp"}>{d.time}</p>
      <p className={d.senderId} key={d.idCount} ref={d.idCount}>
        {" "}
        {d.text}{" "}
      </p>
    </div>
  ));

0 个答案:

没有答案