簡體   English   中英

React組件構造函數和componentWillReceiveProps中的公共代碼

[英]Common code in React component constructor and componentWillReceiveProps

在使用有狀態的React組件時,我經常遇到這種情況。

我需要對props進行一些操作 - 要么做一些我現在想要在render()處理,要么根據props中的值設置狀態。

正如我想在組件最初安裝時以及更新道具時這樣做時,我最終會得到一個類似這樣的樣板代碼:

constructor(){
    super(props)
    const modifiedProps = doSomethingWithProps(props)
        ...
    this.state = {initialState}
}

componentWillReceiveProps(nextProps) {
    const modifiedProps = doSomethingWithProps(nextProps)
         ...
    this.setState({newState})
}

doSomethingWithProps(props){
        ...
}

有沒有更好的方法來做到這一點?

根據問題的評論回答,我覺得很有幫助 -

如果需要基於props完成大量工作, componentWillMount允許您在輔助函數中使用this.setState()並最小化在constructor完成的工作。 這可以清理一堆其他重復的代碼。

constructor(){
    super(props)
    this.state = {initialState}
}

componentWillMount() {
    this.doSomethingWithProps(this.props);
}

componentWillReceiveProps(nextProps) {
    this.doSomethingWithProps(nextProps)
}

doSomethingWithProps(props){
    ...
    this.setState({newState})
}

為什么不在轉換之后將道具傳遞給組件?

這可以通過以下幾種方式實現:

  1. 使用一個簡單的無狀態容器,它可以轉換道具並將它們傳遞給這個組件。

     export const Container = (props) => <YourComponent modifiedProp={doSomethingWithProps(props)} /> 
  2. 使用連接的組件並在mapStateToProps方法中進行轉換:

     const mapStateToProps = (state, ownProps) => ({ modifiedProp: doSomethingWithProps(ownProps) }); export const ConnectedComponent = connect(mapStateToProps)(YourComponent); 

第一個選項實際上是第二個選項的精簡版。

您可能還有興趣使用選擇器來計算傳遞給組件的派生道具。

暫無
暫無

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

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