【问题标题】:Redux store not updating component view on state changeRedux 商店不更新状态更改的组件视图
【发布时间】:2019-01-04 19:42:09
【问题描述】:

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

我可以通过日志中间件看到操作被正确调用并且商店的状态具有新值。如果我使用 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;
}

【问题讨论】:

  • 你的组件有 shouldComponentUpdate 方法吗?
  • 目前没有,但我尝试添加它并返回 true,但没有运气。
  • 你的组件是什么样的?你在什么环境(DOM 或 Native)?
  • 我将更新 OP 中的组件,但它在 DOM 中
  • 你在更新数组吗?

标签: javascript reactjs redux react-redux


【解决方案1】:

代码没问题。将 react-dom npm 依赖项从 16.4.2 升级到 16.7.0 解决了这个问题。

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 2019-12-29
    • 2017-05-31
    相关资源
    最近更新 更多