首页 > 解决方案 > Redux 商店不更新状态更改的组件视图

问题描述

我在状态更改到商店后无法呈现视图时遇到问题。

我可以通过日志中间件看到正确调用了这些操作,并且商店的状态具有新值。如果我使用 react-router 导航到另一个页面,然后返回,用户会从商店正确显示,所以我知道这mapStateToProps是有效的。

我的组件

const mapStateToProps = (state) => {
    return {
        users: state.users.all
    };
};

const actionCreators = {
    fetchUsers
};

export class Users extends React.Component<UsersProps, UsersState> {
    constructor(props) {
        super(props);

        this.state = {           
            // initial values
        };
    }

    componentDidMount() {
        this.props.fetchUsers();
    }

    render() {
        // return PrimeReact DataTable with users prop
    }
}

export default compose(
    withRouter,
    connect(mapStateToProps, actionCreators),
    injectIntl,
)(Users);

行动

export function fetchUsers() {
    return async dispatch => {
        const users = await new UserService().users();
        return dispatch(receiveUsers(users));
    };
}

function receiveUsers(users: User[]) {
    return { users, type: RECEIVE_USERS };
}

减速器

export default combineReducers({
    users
});

function users(state, action) {
    switch (action.type) {
        case RECEIVE_USERS:
            return {
                ...state,
                all: action.users,
            };
        default:
            return state;
    }
}

店铺

export default function configureStore(preloadedState) {
    const middlewares = [
        loggerMiddleware,
        thunkMiddleware,
    ];
    const middlewareEnhancer = applyMiddleware(...middlewares);

    const store = createStore(reducer, middlewareEnhancer);

    return store;
}

标签: javascriptreactjsreduxreact-redux

解决方案


代码没问题。react-dom将npm 依赖项从升级16.4.216.7.0修复问题。


推荐阅读