簡體   English   中英

如何在第一次加載頁面之前在反應中調用動作?

[英]How to call action in react before the first load of page?

我在componentDidMount中有一個通過單擊調用的操作

onBtnClick = (data: any) => {
  this.props.componentDidMount(data);
};

<button onClick={this.onBtnClick}> Toogle posts </button>;
{
  this.props.data.map((el: any) => <li key={el.id}>{el.title}</li>);
}

如何在第一頁加載之前調用componentDidMount 不使用 onClick 函數

componentDidMount是 React 中的生命周期方法,在組件渲染成功后調用。 您不應該將此屬性傳遞給任何其他組件。

如果您希望在頁面完全加載之前調用函數或操作(在調用 componentDidMount 之前),則需要使用UNSAFE_componentWillMount() ,該方法已被棄用,建議您不要使用它。 或者您可以直接在constructor()方法中調用該操作。 構造函數是第一個被調用的東西。

另一件重要的事情是,你不應該從onClick()函數調用生命周期方法,它們由 React 本身適當地處理和調用。

如果您需要將組件作為道具傳遞。 創建一個名為myCustomComponentDidMount()的函數,而不是componentDidMount() ,然后在應用程序第一次加載之前從constructor()調用它,然后你也可以將該函數作為 prop 傳遞給其他人,而不會與componentDidMount()

看看下面的代碼結構。 對於 Redux,您需要react-redux包中提供的connect()函數。 當調用connect()函數時,您的 redux 狀態會自動映射到組件的道具,因此您不需要再次傳遞道具,也不需要componentDidMount()componentWillMount() 只需引用this.props。

我還添加了一些評論供您參考。

// Initial internal state of the component.   
  state = {}

  toggleButton() {
    // do something when the button is clicked.   }

  componentWillMount() {
    // DEPRECATED METHOD
    // Anything you want to call before the component mounts.   }

  componentDidMount() {
    // Anything you want to call after the component mounts.   }

  render() {
    return (
      <div>
        <button onClick={this.onBtnClick}>Toggle posts</button>

        <ul>
          { 
            // check that the data is available before rendering.
            this.props.data && this.props.data.map(el => (
            <li key={el.id}>{el.title}</li>
          ))
          }
        </ul>

      </div>
    )   } }

// If using Redux, you will need to use mapStateToProps()

const mapStateToProps = state => ({ data: state.data })

connect(mapStateToProps)(/* Your component */ )

希望這有助於React-Redux Doc

暫無
暫無

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

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