简体   繁体   中英

How to rewrite a class component to a component that uses hooks

I need help with how to rewrite a component from being a class-component to be a component that instead uses react-hooks. React hooks and react redux is how I an used to writing code, so that part I know. But what I need to learn is more about how a class component works, so that I easier can adapt knowledge from tutorials and material that is a little older.

If anyone have advice of tips on how to rewrite it OR tips on easy reading material or videos that can explain the difference between classes and components that uses hooks. It would be very helpful. Thank you!

An example of the code I want to rewrite looks like this. If anyone knows how to rewrite parts of this example that to would be helpful:

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

The minimal effort approach is to just switch the old way of handling state to the react-hook way.

Start with:

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

Now you use setGrid(), setGameWon() instead of this.setState()

You can also combine the two states into a single state-object

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