首页 > 解决方案 > React-redux componentDidUpdate() 不起作用

问题描述

当 redux 状态发生变化时,componentDidUpdate() 不会触发。
当 redux 使用动作 INIT_GAME 初始化游戏时,有时 componentDidUpdate 没有触发。
当玩家进入游戏时,websocket 向他发送有关当前游戏的信息,redux 调用 INIT_GAME 动作并将空游戏状态更改为正确的当前状态。

游戏.jsx

import React, { PureComponent } from 'react';
import { connect } from 'react-redux';

class Game extends PureComponent {
   componentDidUpdate() {... when INIT_GAME fired, componentDidUpdate sometimes didn't react for this ...}
   render() { return(...) }
}

const mapStateToProps = state => ({
    game: state.game
});

export default connect(mapStateToProps, { })(Game);

gameReducer.js

import { INIT_GAME, PLAY_GAME, TIMER_GAME, ROLL_GAME, CLOSE_GAME } from '../actions/gameActions/types';

const initialState = {
    status: "closed",
    time: null,
    players: []
};

export default function(state = initialState, action) {
    switch (action.type) {
        case INIT_GAME:
            return {
                ...state,
                game: action.payload,
                status: action.payload.roll !== null ? "rolling" : "playing"
            }
        case PLAY_GAME:
            return {
                ...state,
                status: "playing",
                players: [
                    ...state.players,
                    action.payload
                ]
            }
        case TIMER_GAME:
            return {
                ...state,
                time: action.payload,
                status: "playing"
            }
        case ROLL_GAME:
            return {
                ...state,
                status: "rolling"
            }
        case CLOSE_GAME:
            return {
                time: null,
                status: "closed"
            }
        default:
            return state
    }
}

标签: reactjsreduxreact-redux

解决方案


推荐阅读