为什么使用Redux无法正确更改状态?

时间:2018-10-05 12:13:51

标签: javascript reactjs debugging redux react-redux

我制作了一个井字游戏,用户与计算机。即使不使用Redux,它也可以正常工作,但是自从将Redux集成到其中之后,情况就不妙了。

我要实现的目标是:如果有一个空的正方形,则CPU将O随机放置在一个空的位置(在用户放置X之后),但这一次使用Redux

我认为是引起问题的原因let turnState = this.props.turnValueReducerRedux(this.state.turn);和/或我的turnReducer.js文件不正确。

我已经标记了// START HERE// END HERE来指出我认为问题可能出在哪里。

我在做什么错,我该如何解决?

这里是Board.js

import React, { Component } from 'react';
import './Board.css';
import { connect } from 'react-redux';
import * as actionTypes from '../../store/actions/actions';

class Board extends Component {
    constructor(props) {
        super(props);
        this.state = {
            winner: undefined,
        };

        this.gameState = {
            turn: 'X',
            gameLocked: false,
            gameEnded: false,
            board: Array(9).fill(''),
            totalMoves: 0
        }

        this.clicked = this.clicked.bind(this);
    }


    clicked(box) {
        if(this.gameState.gameEnded || this.gameState.gameLocked) {
            return;
        }

        // START HERE 
        let turnState = this.props.turnValueReducerRedux(this.gameState.turn);

        if(this.gameState.board[box.dataset.square] === '') {
            this.gameState.board[box.dataset.square] = turnState;
            box.innerText = this.gameState.turn;

            this.gameState.turnState = this.gameState.turnState === 'X' ? 'O' : 'X';
            this.gameState.totalMoves++;
        }
        // END HERE

        console.log("this.gameState.totalMoves ==> " + this.gameState.totalMoves);

        var result = this.checkWinner();

        if(result === 'X') {
            this.gameState.gameEnded = true;
            this.setState({
                winner: 'X',
                winnerLine: 'X wins'
            });
            console.log("X wins");
        } else if(result === 'O') {
            this.gameState.gameEnded = true;
            this.setState({
                winner: 'O',
                winnerLine: 'O wins'
            });
            console.log("O wins");
        } else if(result === "draw") {
            this.gameState.gameEnded = true;
            this.setState({
               winner: 'draw',
               winnerLine: 'match is a draw'
            });
        }
        console.log("result ==> " + result);

        if(this.gameState.turnState === 'O' && !this.gameState.gameEnded) {
            this.gameState.gameLocked = true;

            setTimeout(() => {
                do {
                    var random = Math.floor(Math.random() * 9);
                } while(this.gameState.board[random] !== '');

                this.gameState.gameLocked = false;
                console.log("reached here");
                this.clicked(document.querySelectorAll('.square')[random]);
            }, 3000)
        }
    }

    render() {
        return(
            <div id="game">
                <div id="state">{this.state.winnerLine}</div>
                <div id="head">
                    Tic Tac Toe
                </div>

                <div id="board" onClick={(e) => this.clicked(e.target)}>
                    <div className="square" data-square="0"></div>
                    <div className="square" data-square="1"></div>
                    <div className="square" data-square="2"></div>
                    <div className="square" data-square="3"></div>
                    <div className="square" data-square="4"></div>
                    <div className="square" data-square="5"></div>
                    <div className="square" data-square="6"></div>
                    <div className="square" data-square="7"></div>
                    <div className="square" data-square="8"></div>
                </div>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        turnValue: state.turnValue
    };

};

const mapDispatchToProps = dispatch => {
    return {
        turnValueReducerRedux: (value) => dispatch({type: actionTypes.TURN_VALUE, value})
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Board);

这里是turnReducer.js

import * as actionTypes from '../actions/actions';

const initialValue = {
    turnValue: 'O'
};

const turnReducer = (state = initialValue, action) => {
    switch (action.type) {
        case actionTypes.TURN_VALUE:
            console.log("turnReducer ==> " + action.value);
            return {
                ...state,
                turnValue: action.value
            };
        default:
            return state;
    }
}

export default turnReducer;

1 个答案:

答案 0 :(得分:0)

我认为关联的分派操作(turnValueReducerRedux)将不会返回您期望的结果。它将返回完整的动作({ type: '...', value: ... }),而不仅仅是返回值,这意味着在以下代码中turnState将是错误的:

let turnState = this.props.turnValueReducerRedux(this.state.turn);

if(this.gameState.board[box.dataset.square] === '') {
  this.gameState.board[box.dataset.square] = turnState;

作为一般建议,您似乎并不依赖state或商店来呈现数据,这是React的主要职责之一。因此,您将通过分派操作来在存储中设置值,但不要使用this.state.turnValue来访问它,它由以下代码定义:

const mapStateToProps = state => {
    return {
        turnValue: state.turnValue
    };
};

还请注意,gameStatestate有很大的不同,因为后者将触发重新渲染并连接到商店,而前者则不会。


更新


根据下面的讨论,这是一个采用不同方法的示例:https://codesandbox.io/s/x2x773pqxz

自动计算机播放器是复杂的部分,因为这是人类播放器的动作的副作用。因此,我添加了redux-thunk以允许某些操作触发其他操作。我已经延迟了计算机的转动,以便您可以看到它的运行情况。

我还将董事会和各个Square拆分为单独的组件,这两个组件仅用于演示。 Game组件和redux/actions.js文件是最重要的。

理论上,您可以选择自己喜欢的棋盘大小和玩家人数,但是CSS只是为3x3棋盘设置的。

我没有实现findWinner逻辑,因为这感觉太费力了

让我知道我是否可以澄清任何事情,希望对您有所帮助!