簡體   English   中英

當父狀態更改時,React子道具不會更新

[英]React child props doesn't update when parent state change

所以這是主要的問題:我打開一個websocket,需要在第一個即將到來的消息中讀取sessionId,以便將其用於進一步發送的消息。 因此,這僅需要執行一次。

我有一個子組件“ processMessage”,看起來像這樣:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ChatBot from 'react-simple-chatbot';

export class ProcessMessage extends Component {
  constructor(props) {
     super(props);

     this.state = {
       messages: [],
     };
   }

  componentWillMount() {
    const input = {
      type: 'user',
      sessionId: this.props.sessionId,
      msg: this.props.inputMessage,
    };
    //send message to websocket
    this.props.connection.send(input)

    this.props.connection.onmessage = evt => {
      // add the new message to state
      const msg = JSON.parse(evt.data);

      let responseText = msg.msg;
      this.setState({
        messages : responseText
      })
    };



  }


  render() {
    return <div>{ this.state.messages}</div>;
  }
}

以及一個“ app”父對象,它打開websocket並獲取如下所示的sessionId組件(不發布所有內容):

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ProcessMessage } from './components/processMessage.js';

export class App extends React.Component {
  constructor(props) {
    super(props);
    // Assign state itself, and a default value for items


  }
    componentWillMount() {
        const url = 'ws://localhost:4040';

        // this open websocket service
        this.connection = new WebSocket(url);

        this.setState(
          { connection:this.connection }
        );
        var sessionId;
        // listen to onmessage event
        this.connection.onmessage = evt => {

        // add the new message to state
          const msg = JSON.parse(evt.data);
            if (msg.type = "sessionId") {
              sessionId=msg.msg;
              console.log("now received sessionId " +sessionId);
              this.setState(
                { sessionId: sessionId}
              );

            }
        };
  }

  render(){
  return <ProcessMessage sessionId={this.state.sessionId} connection={this.state.connection} inputMessage={this.state.inputMessage}/>
  }

因此,有效的方法是使用連接道具(套接字打開)正確發送了消息,但在子組件中未定義sessionId,因為它會花費一些時間來收到我獲得sessionId的套接字的第一個響應,但是組件沒有似乎用新的道具重新渲染了。

我也嘗試放入子組件processMessage:

componentWillReceiveProps(nextProps) {
  this.setState({ sessionId: nextProps.sessionId});  
}

沒有成功。 我是否缺少明顯的東西?

您應該使用componentDidMount生命周期函數作為componentWillMount中的設置狀態不會觸發重新rerender ,因此道具不會更新

React文檔中:

componentWillMount()

在掛載發生之前立即調用componentWillMount() 在render()之前調用它,因此在此方法中同步設置狀態不會觸發重新渲染 避免在此方法中引入任何副作用或訂閱。

這是在服務器渲染上調用的唯一生命周期掛鈎。 通常,我們建議改為使用constructor()

componentDidMount() {
        const url = 'ws://localhost:4040';

        // this open websocket service
        this.connection = new WebSocket(url);

        this.setState(
          { connection:this.connection }
        );
        var sessionId;
        // listen to onmessage event
        this.connection.onmessage = evt => {

        // add the new message to state
          const msg = JSON.parse(evt.data);
            if (msg.type = "sessionId") {
              sessionId=msg.msg;
              console.log("now received sessionId " +sessionId);
              this.setState(
                { sessionId: sessionId}
              );

            }
        };
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM