首页 > 解决方案 > 为什么我的 Redux 根本不会改变状态?

问题描述

为了查看 Redux 是否正常工作,checkWinner()我正在检查内部console.log("win value (is redux working?) ==> " + win);,输出始终是:

win value (does redux work?) ==> [object Object]

输出应该是win value (does redux work?) ==> X. 我的 Reducer 写错了吗?

这是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
        }
    }

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

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

            this.gameState.turn = this.gameState.turn === 'X' ? 'O' : 'X';
            this.gameState.totalMoves++;
        }

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

        var result = this.checkWinner();

        // my attempt
        if(result === 'X') {
            this.gameState.gameEnded = true;
            let win = this.props.winnerValueRedux(this.state.winner);
            this.setState({
                winner: win,
                winnerLine: 'X wins'
            });
            console.log("win value (is redux working?) ==> " + win);
            console.log("X wins");
        // end of attempt

        } 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.turn === '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 {
        winnerValue: state.winnerValue
    };
};

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


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

这是winnerReducer.js

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

const initialState = {
    winnerValue: undefined
};

const winnerReducer = (state = initialState, action) => {
    console.log("[winnerReducer] => " + action.value);
    switch(action.type) {
        case actionTypes.WINNER_VALUE:
            return{
                ...state,
                winnerValue: action.value
            };
        default:
            return state;
    }
}

export default winnerReducer;

标签: javascriptreactjsdebuggingreduxreact-redux

解决方案


调用这些代码后:

let win = this.props.winnerValueRedux(this.state.winner);
console.log("win value (is redux working?) ==> " + win);

结果是:

win value (does redux work?) ==> [object Object]

使用后JSON.stringify(),我发现[object Object]{"type":"WINNER_VALUE"}实际上是调度的动作,我们没有看到value这个动作中存在的属性,因为它的值是undefined

还有你的问题:

输出应该是赢值(redux 工作吗?)==> X。我的 Reducer 写错了吗?

一切都很好,没有任何问题。错误的是我们期望win变量的值应该是什么。

let win = this.props.winnerValueRedux(this.state.winner)

相当于:

function winnerValueRedux(value){
   return dispatch({type: actionTypes.WINNER_VALUE, value})
}

let win = winnerValueRedux(value);

而且,这是关键,dispatch(action)方法的返回值是调度的动作,它是一个对象。这就是为什么您会收到:win value (does redux work?) ==> [object Object]

更多信息:调度(动作)


现在,我们明白为什么我们会收到这个意想不到的结果。

下一部分是检查我们的 redux 存储是否工作。

我已经检查过了,它有效。这是演示:https ://codesandbox.io/s/6xlv5rvqqk

这是我用来向 redux store 发送操作的代码:

if (result === "X") {
  this.gameState.gameEnded = true;
  this.props.winnerValueRedux("X");   //dispatch an action
} else if (result === "O") {
  this.gameState.gameEnded = true;
  this.props.winnerValueRedux("O");   //dispatch an action
} else if (result === "draw") {
  this.gameState.gameEnded = true;
  this.props.winnerValueRedux("draw");  //dispatch an action
}

这是我用来获取 redux 状态的代码

<div id="state">{this.props.winnerValue}</div>   // get value from redux store

我已经尽力了。希望这会有所帮助。


推荐阅读