我需要帮助如何将组件从类组件重写为使用react-hooks的组件。 React hooks 和 React redux 是我习惯编写代码的方式,所以我知道这一部分。但我需要更多地了解类组件的工作原理,以便我更容易地适应教程和较旧的 Material 中的知识。
如果有人有关于如何重写它的提示建议,或者关于简单阅读 Material 或视频的提示,可以解释使用钩子(Hook)的类和组件之间的区别。这会很有帮助。谢谢!
我想要重写的代码示例如下所示。如果有人知道如何重写此示例的部分内容,将会有所帮助:
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
最佳答案
最简单的方法是将处理状态的旧方式切换为react-hook方式。
开头:
const [grid, setGrid] = useState(game.init({ size: this.props.size }));
const [gameWon, setGameWon] = useState(false);
现在您使用 setGrid()、setGameWon()
而不是 this.setState()
您还可以将两种状态组合成一个状态对象
关于javascript - 如何将类组件重写为使用钩子(Hook)的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60889439/