【发布时间】:2017-12-29 00:10:59
【问题描述】:
React 新手,使用 Create React App 创建了一个简单的井字游戏,但遇到以下问题:
- 单击正方形后,“X”和“O”无法出现在 DOM 中
-
currentTurn属性不会改变,它始终保持轮到 X 的状态
在下面的代码中,如果我将 console.log(this.state.board) 添加到 handleClick() 函数,board 数组会发生变化,但它都是 X。有什么想法吗?
这是我的 App.js:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props)
this.state = {
PLAYER_ONE_SYMBOL: "X",
PLAYER_TWO_SYMBOL: "O",
currentTurn: "X",
board: [
"", "", "", "", "", "", "", "", ""
]
}
}
handleClick(index) {
var this_board = this.state.board;
this_board[index] = this.state.currentTurn;
this.setState = ({
board: this.state.board,
currentTurn: this.state.currentTurn === this.state.PLAYER_ONE_SYMBOL ? this.state.PLAYER_TWO_SYMBOL : this.state.PLAYER_ONE_SYMBOL
})
}
render() {
return (
<div className="board">
{this.state.board.map((cell, index) => {
return <div onClick={() => this.handleClick(index)} className="square">{cell}</div>;
})}
</div>
);
}
}
我的 App.css:
.board {
display: flex;
width: 600px;
height: 600px;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
}
.square {
display: flex;
height: 200px;
width: 200px;
box-sizing: border-box;
border: 5px solid black;
font-size: 5em;
justify-content: center;
align-items: center;
}
.square:hover {
cursor: pointer;
background-color: #80cd92;
}
编辑:意识到我犯了一个愚蠢的错误,将this.setState 视为表达式而不是函数并且编写了错误的语法。这有效:
this.setState({
board: this.state.board,
currentTurn: this.state.currentTurn === this.state.PLAYER_ONE_SYMBOL ? this.state.PLAYER_TWO_SYMBOL : this.state.PLAYER_ONE_SYMBOL
})
【问题讨论】:
-
发生这种行为是因为你正在变异
this.state -
this.setState是一个函数。您需要传递一个对象而不是为其分配一个值。所以this.setState = ({ board: this.state.blah })应该是this.setState({ board: this.state.blah })。 -
@norbertpy 这应该是一个答案而不是评论:)
-
@Kunukn,没有人有时间。
-
@norbertpy 谢谢刚刚意识到我在语法上犯了一个愚蠢的错误,为我的问题添加了一个编辑
标签: javascript reactjs jsx create-react-app