简体   繁体   中英

Grid Size isn't changing properly in React when changing state

I'm trying to change the grid size on my Conway game of life app but when I click button to set new numCols/numRows only one of them is effected on the app. How do I affectively set new state so grid changes size as expected.

I have 2 buttons in the app, one to make grid smaller, one to make it bigger. onClick they Trigger function sizeHandler & sizeHandler2.

My guess is I need to set new state in a different method but I tried a few methods to no avail.

import React, { useState } from 'react'
import './App.css';

function App() {

  const color = "#111"

  const [numRows, setNumRows] = useState(20)
  const [numCols, setNumCols] = useState(20)
 
  const generateEmptyGrid = () => {
    const rows = [];
    for (let i = 0; i < numRows; i++) {
      rows.push(Array.from(Array(numCols), () => 0))
    }
    return rows
  }

  const [grid, setGrid] = useState(() => {
    return generateEmptyGrid();
  })

  const sizeHandler = () => {
    setNumRows(40)
    setNumCols(40)
  }

  const sizeHandler2 = () => {
    setNumRows(20)
    setNumCols(20)
  }

  // RENDER
  return (
    <div className="page">
      <div className="title">
        <h1>
          Conway's Game Of Life
        </h1>

        <button onClick={sizeHandler}>
          Size+
        </button>

        <button onClick={sizeHandler2}>
          Size-
        </button>

      </div>

      <div className="grid" style={{
          display: 'grid',
          gridTemplateColumns: `repeat(${numCols}, 20px)`
        }}>
        {grid.map((rows, i) => 
          rows.map((col, j) => 
            <div className="node"
            key={`${i}-${j}`}
            style={{
              width: 20,
              height: 20,
              border: 'solid 1px grey',
              backgroundColor: grid[i][j] ? color : undefined
            }} 
            />
          ))}
      </div>
    </div>
  );
}

export default App;

What you are doing is you want a change of numRows and numCols to have a side effect. You actually almost said it yourself. React has a hook for that: useEffect :

useEffect(() => {
  setGrid(generateEmptyGrid())
}, [numRows, numCols]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM