簡體   English   中英

在渲染后使用getOffsetHeight和異步數據

[英]using getOffsetHeight with async data after render in react

下面的代碼很簡單,但是我認為這是不適當的。 基本上,我嘗試計算列表的高度。 但是,比進行setTimeout hack更好的解決方案是什么? 我嘗試了componentDidMount,但這不能保證數據已加載。

class App extends Component {
  constructor() {
    super();

    this.state = {
      users: null
    };
  }

  componentWillMount() {
    axios.get("https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")
      .then(response => this.setState({ users: response.data }));
  }

  componentDidMount() {
    setTimeout(() => {
      console.log(this.userElem.offsetHeight);
    }, 1000);
  }

  render() {
    return (
      <div style={styles}>
        <div ref={elem => (this.userElem = elem)}>
          {this.state.users &&
            this.state.users.map(o =>
              <p>
                {o.first}
              </p>
            )}
        </div>
      </div>
    );
  }
}

演示https://codesandbox.io/s/j46o2656vy

而不是在componentWillMount內部進行api調用,而是在componentDidMount方法內部進行,而是使用setState回調方法檢查元素的高度。

像這樣:

componentDidMount() {
    axios.get("https://randomapi.com/api/6de6abfedb24f889e0b5f675edc50deb?fmt=raw&sole")
    .then(response => {
        this.setState({ users: response.data }, () => {
            console.log(this.userElem.offsetHeight);
        }) 
    });
}

或者,您也可以使用componentDidUpdate方法,該方法在更新發生后立即被調用。 初始渲染不調用此方法。

你可以使用componentDidUpdate並檢查您的this.userElem.offsetHeight變量there.Also,我會改變componentWillMountcomponentDidMount。 您可以在這里閱讀更多內容。

暫無
暫無

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

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