为什么我的Redux更改状态根本不会更改?

时间:2018-10-07 14:40:50

标签: javascript reactjs debugging redux react-redux

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

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

输出应为win value (does redux work?) ==> X。我的减速机写错了吗?

这里是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;

2 个答案:

答案 0 :(得分:1)

调用以下代码后:

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"},实际上是已分派的操作,我们没有看到{{1 }}属性存在于此操作中,因为它的值是 undefined

您的问题:

  

输出应为获胜值(redux是否起作用?)==>X。   写错了吗?

一切都很好,没有错。我们期望value变量的值应该是错误的。

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)

有关更多信息:dispatch(action)


就目前而言,我们了解为什么收到了意外结果。

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

我已经检查了它,而且效果很好。这是演示:https://codesandbox.io/s/6xlv5rvqqk

这是我用来将操作分派到redux存储的代码:

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

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

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
}

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

答案 1 :(得分:0)

winner传递错误或未更新的参数(应该是winnerValueRedux()?)是一个小问题。

主要问题不在于“ redux流”:

调度程序不返回值,它发出消息/动作。减速器处理的动作正在更新商店中的状态。更新的值由mapStateToProps“返回”到组件。

搜索一些教程/示例。