棋盘组件生命周期

时间:2020-10-31 20:37:22

标签: javascript reactjs components

我正在尝试创建一个棋盘格,该棋盘格在给定整数作为输入的情况下调整大小,并通过int Checkerboard返回一个int作为输出。当前,我的棋盘会从状态为set的默认状态为8的设置变量进行渲染,但是每次我尝试添加输入时,应用都会崩溃。我正在尝试找到一种更有效地理解组件生命周期的方法。下面是我的棋盘组件的代码。

import React, { Component } from 'react'


class Checkerboard extends Component {

  constructor(props) {
    super(props)
    this.state = {
      checkers: [],
      size: 8,
      input: null
    }
    this.handleSubmit = this.handleSubmit.bind(this)
    this.handleChange = this.handleSubmit.bind(this)
  }


  // This function divides the squares from state into rows and draws the board
  drawBoard = (squares) => {
    console.log("drawBoard running...")
    console.log("drawing board from state:", squares)
    let rows = []
    for (let i=0; i<squares.length; i+=this.state.size) {
      rows.push(squares.slice(i,i+this.state.size));
    }
    console.log("Rows: ", rows)
    return (rows.map(row => (
      <div className="row" style = {{ display: 'flex' }}>
        {row.map(square =>(
          <div className="square" key = {square.key} style = {{
            backgroundColor: `${square.color}`,
            height: '50px',
            width: '50px',
            margin: '0 auto',
            display: 'inline-block',
          }}>
          </div>
        ))}
      </div>
    )))
  }


  addSquares = (col) => {
    console.log("adding squares...")
    let squares = []
    for (let i=0; i<(col ** 2); i++) {
      if ((((Math.floor(i/this.state.size)+1)%2))!== 0){
        if (((i-((Math.floor(i/this.state.size))*col)+1)%2) !==0){
          squares.push( { key: i, row: Math.floor(i/this.state.size), column: i-((Math.floor(i/this.state.size))*col), color: "white" } )
          continue
        } else {
          squares.push( { key: i, row: Math.floor(i/this.state.size), column: i-((Math.floor(i/this.state.size))*col), color: "black" } )
          continue
        } 
      }
      else if (((Math.floor(i/this.state.size)+1)%2) === 0) {
        if (((i-((Math.floor(i/this.state.size))*col)+1)%2) !==0){
          squares.push( { key: i, row: Math.floor(i/this.state.size), column: i-((Math.floor(i/this.state.size))*col), color: "black" } )
          continue
        } else {
          squares.push( { key: i, row: Math.floor(i/this.state.size), column: i-((Math.floor(i/this.state.size))*col), color: "white" } )
          continue
        }
      }
    }
    console.log(squares)
    return this.setState({ checkers: squares })
  }

  componentDidMount() {
    this.addSquares(this.state.size)
  }

  handleChange(event) {
    this.setState({ input: event.target.value})
  }

  handleSubmit(event) {
    event.preventDefault()
    this.setState({ size: this.state.input})
    console.log(this.state.size)
  }


  render() {
    return (
      <div className="checkerBoard" style={{overflow: 'hidden'}}>
        {this.drawBoard(this.state.checkers)}
        <form onSubmit={this.handleSubmit}>
          <input placeholder="Enter desired dimensions" type="integer" onChange={this.handleChange}></input>
          <button type="submit">Submit</button>
        </form>
      </div>
    )   
  }

}
export default Checkerboard;

2 个答案:

答案 0 :(得分:0)

“ ...我正在尝试找到一种更有效地理解组件生命周期的方法...”

我已经阅读了您的代码(没有遍历addSquares()中的数学知识),并且在您的生命周期内,我看到了这种模式:

  1. 组件安装
  2. state加载
  3. 给定一个addSquares()值,componentDidMount()调用
  4. state
  5. 您的组件现在正在以用户身份等待您的回复。
  6. 您设置了一个数字,因此一次更改了state,从而导致渲染。
  7. 您单击提交,从而再次更改state,从而导致另一个渲染。
  8. 您的应用程序崩溃!

我希望我做对了,如果是的话,我可以想到它崩溃的原因之一: 您的正方形永远不会重新渲染,因为定义它们的唯一东西是componentDidMount(),其名称为componentDidUpdate(),仅在安装(一次)时调用。您可以使用addSquares()再次呼叫@patch.object

答案 1 :(得分:0)

我稍微玩了一下您的代码。当我更换东西时,我一直在运行handleSubmit函数,因此让我认为您的bind语句在顶部有问题。

我喜欢创建大小合适的棋盘的想法。并不是真正解决问题的答案,但是如果您想检查出它,最终会用钩子进行重构。

https://codesandbox.io/s/sweet-hellman-u4gvf?file=/src/App.js