如何将类组件重写为使用钩子的组件

时间:2020-03-27 15:48:05

标签: javascript reactjs

我需要有关如何将组件从类组件重写为使用React-hooks的组件的帮助。 React钩子和React Redux是我习惯于编写代码的方式,因此我知道这一部分。但是,我需要学习的更多是关于类组件的工作方式,以便我可以轻松地从教程和较旧的材料中吸收知识。

如果有人对如何重写建议有任何建议,或者对易于阅读的材料或视频提出了建议,可以解释使用钩子的类和组件之间的区别。这将非常有帮助。谢谢!

我要重写的代码示例如下所示。如果有人知道如何重写本示例的部分内容,将会有所帮助:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

import Grid from './Grid'
import Controls from './Controls'
import { game } from './game'

import './puzzle.css'

class Puzzle extends Component {
  static propTypes = {
    size: PropTypes.number
  }

  static defaultProps = {
    size: 4
  }

  state = {
    grid: game.init({ size: this.props.size }),
    gameWon: false,
  }

  onCellClick = (index) => {
    const [grid, isWon] = game.swapCell(index)
    this.setState(() => ({ grid, gameWon: isWon }))
  }

  restart = (type) => { this.setState(() => ({ grid: game.reset(type), gameWon: false })) }

  render() {
    const { grid, gameWon } = this.state

    return (
      <>
        { gameWon
          ? <div className="win">Grattis!</div>
          : <Grid items={grid} onClick={this.onCellClick}/>
        }
        <Controls restart={this.restart}/>
      </>
    )
  }
}

export default Puzzle

1 个答案:

答案 0 :(得分:1)

省力的方法是将处理状态的旧方法切换为反应挂钩方法。

开始于:

const [grid, setGrid] = useState(game.init({ size: this.props.size }));
const [gameWon, setGameWon] = useState(false);

现在,您使用setGrid(), setGameWon()代替this.setState()

您还可以将两个状态组合成一个状态对象