【发布时间】:2021-12-02 19:47:56
【问题描述】:
我正在尝试重构一个类组件,但在第一类中,有一个带有 map 的状态,我尝试将其更改为 Functional 并使用 useState,但它一直给我这个错误
ReferenceError: Cannot access 'rules' before initialization
当我尝试使用 map 将规则状态(我不确定如何)重构为 useState 时,就会发生这种情况。它甚至是为地图分配状态的正确方法吗?我该如何解决?
类组件:
import Rule from "./Rule";
class Game extends Component {
state = {
dices: Array(this.props.nOfDices).fill(1),
locked: Array(this.props.nOfDices).fill(false),
rotation: Array(this.props.nOfDices).fill(0),
rollsRemaining: 3,
isRolling: false,
rules: this.props.rules.map( r => ({...r})),
score: 0,
bestScore: window.localStorage.getItem("bestScore") || "0"
};
componentDidMount() {
this.roll();
};
我重构的功能组件:
const Game = ({ nOfDices }) => {
const [isRolling, setisRolling] = useState(false);
const [score, setScore] = useState(0);
const [rollsRemaining, setRollsRemaining] = useState(3);
const [dices, setDices] = useState([Array(nOfDices).fill(1)]);
const [rules, setRules] = useState(rules.map(r => ({ ...r })));
const [bestScore, setBestScore] = useState(window.localStorage.getItem("bestScore") || "0");
const [locked, setLocked] = useState([Array(nOfDices).fill(false)]);
const [rotation, setRotation] = useState([Array(nOfDices).fill(0)]);
useEffect(() => {
roll();
//eslint-disable-next-line
}, []);
【问题讨论】:
标签: javascript reactjs use-state