簡體   English   中英

在對象中將對象綁定為組件狀態鍵值的正確方法

[英]correct way to bind an object as value of a component's state key in react

我正在創建一個minesweeper React應用,並在板有狀態的組件內部進行了初始化,並使用地雷和其他信息填充了板。

該板的初始化如下

// Method that creates a board of empty tiles, populates it with mines and gets the number of neighbouring
// mines for every tile on the board. Returns the initialized board  
initializeBoard(height, width, mines){
    const emptyTiles = this.createEmptyArray(height, width);
    const populatedTiles = this.populateBoard(emptyTiles, height, width, mines);
    const neighbourTiles = this.getNumOfMinesNeighbours(populatedTiles,height, width);
    return this.renderBoard(neighbourTiles);
   }

renderBoard返回一個JSX組件。

我從另一個組件傳遞來的道具收到高度,寬度和地雷。

我的董事會狀態如下:

state = {
    mineCount: this.props.mines,
    gameStatus: null,
    boardData: null
}

我想動態呈現初始化的板並更新boardData鍵的Board狀態值。 現在,我到達了兩種不同的方法:

  1. 在Board的render()方法中動態調用Initialize board(),並以某種方式更新其狀態
  2. 通過調用initializeBoard()直接分配狀態boardData值

方法1在render()中看起來像這樣:

render() {  
    const board= this.initializeBoard(this.props.height, this.props.width, this.props.mines);
    //Save state throws Maximum update depth exceeded.
    return (
        <div>
            {board}
        </div> ...} //end of render

方法2:

state = {
    mineCount: this.props.mines,
    gameStatus: null,
    boardData: this.initializeBoard(this.props.height, this.props.width, this.props.mineCount)
}

現在,我知道在render()中設置組件的狀態是不行 ,但我也找不到合適的生命周期掛鈎 ,當在render()之前創建對象然后將其動態渲染到對象時,該掛鈎將起作用JSX,因為我沒有通過道具接收此對象。

所以我想知道的是

  • 方法2是好的/適當的方法嗎? 還是調用存儲狀態鍵值的方法是一種不好的做法?
  • 關於生命周期掛鈎和在render()之前創建的對象,我是否缺少某些東西?
  • 在這種情況下,是否有任何“最佳實踐”來存儲國家的關鍵值?

方法2是好的/適當的方法嗎? 還是調用存儲狀態鍵值的方法是一種不好的做法?

不,為什么要這樣?

關於生命周期掛鈎和在render()之前創建的對象,我是否缺少某些東西?

不,沒有正當理由要鈎在那里。

在這種情況下,是否有任何“最佳實踐”來存儲國家的關鍵值?

是的,#2。

也許代碼中的更多注釋將幫助我更好地理解問題。

constructor(super) {
   state = {
     mineCount: this.props.mines,
     gameStatus: null,
     boardData: null
   }
   this.board = null
   this.populatedTiles = null;
   this.neighbourTiles = null; 
   this.width = this.props.width;
   this.height = this.props.height; 
}

componentDidMount() {
   this.initializeBoard(this.height, this.width, this.state.mines);
}

initializeBoard(height, width, mines){
   const emptyTiles = this.createEmptyArray(height, width);
   this.populatedTiles = this.populateBoard(emptyTiles, height, width, mines);
   this.neighbourTiles = this.getNumOfMinesNeighbours(populatedTiles,height, width);
}

render() {
   const board = this.renderBoard(this.neighbourTiles, this.state) || null;
   return (
     <div>
        {board}
     </div>
   )
} 

上一張海報回答了您的前兩個問題,我將在第三個問題上稍作擴展。

簡短的答案是#2是更好的做法。

嘗試將其更多地視為面向對象編程問題,而不是反應問題。 您引用的react組件只是react組件類的一個實例。 像任何類一樣,它們具有構造函數。 這個想法是您想在構造函數中進行任何狀態初始化。 您想在首次實例化該類時准備好“真理之源”。

因此,當您第一次設置狀態時,最好在構造函數中進行板初始化。 這樣,您可以避免在第一次實例化該類和嘗試操縱該板之間的任何狀態不一致。 它也更干凈,更容易理解,並且符合典型的OOP原則。

暫無
暫無

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

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