簡體   English   中英

setState 在 componentDidMount() 中不起作用 - React

[英]setState not working in componentDidMount() - React

我在 componentDidMount() 中使用 setState 函數時遇到了一些問題。

我想要做的是:我正在嘗試使 HTML5 圓圈響應(如果瀏覽器窗口更大,則更大,反之亦然)。

到目前為止我所做的:我一直將維度存儲在稱為 containerDim 的狀態中。 默認情況下,這設置為空。 這是我所做的一個非常基本的實現:

class App extends React.Component  {
  constructor(props)  {
    super(props);
    this.state = {containerDim: null};
    this.resizeCircle = this.resizeCircle.bind(this)  //To not loose value of this
  }

  componentDidMount()  {

    var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

    this.setState({
      containerDim: {width:dimensions.width, height: dimensions.height}
    });

   window.addEventListener("resize", this.resizeCircle));

  }

 resizeCircle()  {  //THE RESIZING WORKS, THE initial setting of state doesn't
   var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

    this.setState({
      containerDim: {width:dimensions.width, height: dimensions.height}
    });

 }



  render()  {
    return (
     <div ref={"responsiveContainer"} >
       <Circle dimensions={this.state.containerDim} />
     </div>
    );
  }
} 

//Circle component

class Circle extends React.Component {
  constructor(props)  {
    super(props);
  }

  componentWillReceiveProps()  {

    console.log(this.props.dimensions); //THIS LOGS OUT NULL

  }

  render()  {
    CIRCLE GOES HERE
  }

}

基本上我想用這段代碼做的是獲取“responseContainer”的寬度和高度,並將其作為道具傳遞給<Circle />組件。

以上不起作用,因為 setState 不會改變任何狀態。

任何幫助將不勝感激!

編輯:

這個“有效”但我覺得它不正確,應該有更好的方法:

 var dimensions = window.getComputedStyle(this.refs.container);

  setTimeout(function()  {


  this.setState({
    screenDim:{width:dimensions.width, height:dimensions.height}
  });
}.bind(this),0);

this.setState({
  screenDim:{width:dimensions.width, height:dimensions.height}
});

組件不監聽 didMount 中的狀態修改; 這意味着即使狀態更新,也不會觸發重繪。

你能試試這個嗎?

componentDidMount()  {
    setInterval((function() {
      var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height

      this.setState({
        containerDim: {width:dimensions.width, height: dimensions.height}
      });
    }).bind(this), 1000);
  }

暫無
暫無

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

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