簡體   English   中英

React js 狀態和生命周期

[英]React js state and lifecycle

componentDidMount() {
    const user = auth.getCurrentUser();
    this.setState({ user });
  }

我有這個代碼,我認為this.setState({ user }); 需要一點時間,如果我想立即進行一些檢查,例如

<Route
              path="/foo"
              render={props =>
                this.state.user ? (
                  <Bar {...props} />
                ) : (
                  <Redirect to="/login" />
                )
              }
            />

刷新頁面時,開頭的用戶始終為空。 什么是正確的解決方案? 我需要在constructor設置狀態嗎? 還是我做錯了什么?

我的帳戶被一些否決票問題封鎖,有趣的是我必須重新編輯它們,即使我已經接受了答案。我不明白這樣做有什么意義。我對這個 stackoverflow 系統感到非常沮喪.

現在,我基本上只能繼續編輯我的問題,它們都得到了回答。 這是荒唐的 !!!

是的,您應該在構造函數中初始化您的狀態。

請參閱React 文檔示例

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

刷新頁面時,開頭的用戶始終為空

@Shubham Khatri 確實很好地解釋了它,簡而言之,只是因為render()函數在componentDidMount()之前調用,因此, user始終為空。

看看這個: React 生命周期方法圖

React 生命周期方法圖

正如你所看到的, setState的正確位置應該是contructor()因為它在render()之前被調用。

但是,對於 api 調用,為什么componentDidMount是更好的地方? 為什么我們不在constructor做所有設置?

我知道你在談論這個: https : //reactjs.org/docs/faq-ajax.html 該文檔確實說:您應該在componentDidMount生命周期方法中使用 AJAX 調用填充數據。 這樣您就可以在檢索數據時使用setState來更新您的組件。

然而,在另一個地方,他們說:

您可以在componentDidMount()立即調用setState() componentDidMount() 它會觸發額外的渲染,但它會在瀏覽器更新屏幕之前發生。 這保證即使在這種情況下render()將被調用兩次,用戶也不會看到中間狀態。 請謹慎使用此模式,因為它通常會導致性能問題。 在大多數情況下,您應該能夠在constructor()分配初始狀態。 但是,當您需要在渲染取決於其大小或位置的內容之前測量DOM 節點對於模態和工具提示等情況,它可能是必要的

...以及您需要進行身份驗證的情況,因為此過程取決於user的價值(如您的設計)。

您的代碼中的問題是,在渲染之后調用componentDidMount ,當您的用戶詳細信息被提取並存儲在狀態時,您的組件已准備好重定向到/login因為用戶不可用。 要解決此問題,您需要在初始渲染之前獲取user詳細信息,因此constructor是執行此操作的理想場所

constructor(props) {
   super(props);
   this.state = {
       user: auth.getCurrentUser()
   }
}

狀態進入構造函數內部,但前提是您需要構造函數(例如:初始化標志)。 如果您不需要構造函數,則可以在外部初始化狀態:

class MyComponent extends Component {
    state = { myState = [] }

    render() {
        const { myState } = this.state
        return (...)
    }
}

您應該使用constructor() 來初始化狀態,使用componentDidMount() 來調用函數,使用componentWillReceiveProps() 來初始化setState。

  constructor(props) {
    super(props);
    this.state = {
      firstName: "",
      lastName: ""
    };
  }

  componentDidMount() {
    this.props.userProfile();
  }

  componentWillReceiveProps(nextProps, prevProps) {
    this.setState({
      firstName: nextProps.user.firstName,
      lastName: nextProps.user.lastName
    });
  }

暫無
暫無

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

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