簡體   English   中英

在componentDidMount()上傳遞要更新的參數的函數內部的設置狀態做出反應

[英]React setting state inside function on componentDidMount() passing parameters to be updated

我需要從componentDidMount()中的函數更新組件狀態對象元素。 理想情況下,我希望能夠傳遞我需要更新的元素以及我想用來更新它的值。 我確實知道“ this”是未定義的,並且我已經看到了帶有箭頭功能的解決方案,但是我似乎無法使其正常工作。

從componentDidMount()內部的函數傳遞要更新的元素和值的狀態來更新狀態的最佳方法是什么?

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      obj: {
        itemone: "on",
        itemtwo: "off"
      }
    };
  }

  // updateState(item, valStr) {
  //   this.setState({
  //       obj: {
  //         item: valStr
  //       }
  //   });
  // };

  componentDidMount() { 
      //.......
      websocket.onmessage = function (event) {
        //this.updateState(itemone "off");
        this.setState({ //undefined
            obj: {
              itemone: "off"
            }
        });
      };
  }

  render() {

    return (
      <div className="App">
        ...
      </div>
    );
  }
}

export default App;

嘗試這個

websocket.onmessage = (function (event) {
        //this.updateState(itemone "off");
        this.setState({
            obj: {
              itemone: "off"
            }
        });
}).bind(this);

鑒於你無法使用箭頭功能,可以規避this未來不確定的是:

componentDidMount() { 

// Define a variable pointing to the `this` of the class
const newThis = this
websocket.onmessage = function (event) {
   // Use that this to call the setState
   newThis.setState(prevState => {
      const newObj = prevState.obj
      newObj.itemone = "off"
      return { obj: newObj}
   })
  }
}

您可以嘗試arrow function

websocket.onmessage = (event) => {
    //this.updateState(itemone "off");
    this.setState({ //undefined
        obj: {
          itemone: "off"
        }
    });
  };

暫無
暫無

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

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