首页 > 解决方案 > 类对象在减速器中无法正常工作

问题描述

我有一个用户模型(es6 类),我正在使用新键盘创建一个对象,并将其传递给我的 userReducer 函数的 initialState。如何根据操作更新模型。

例如,如果我尝试发送一个动作来更改isLogginguserModel 中的值,那么记录器中的 prevState 和 nextState 是相同的。

https://i.ibb.co/0CBSZ5v/Screenshot-from-2019-04-19-19-07-44.png

用户减速器

import { USER } from '../constants'
import type { IUserInitialState, IUserAction } from '../types'
import { UserModel } from '../models'

const initialState: IUserInitialState = new UserModel()

export const userReducer = (state: IUserInitialState = initialState, action: IUserAction): Object => {
    console.log(state)
    switch (action.type) {
        case USER.LOGIN_REQUEST:
            console.log(state)
            initialState.userIsLogging = action.payload
            return initialState
        default:
            return state
    }
}

------------------------------
User Action

export const loginRequest = (type: boolean): Object => {
    return {
        type: USER.LOGIN_REQUEST,
        payload: type
    }
}

用户模型

导出类用户模型 {

user: IUserModel = {
    username: '',
    password: '',
    isLogging: false
}

set userModel(userObject: IUserModel) {
    this.user = userObject
}

set userIsLogging(logging: boolean) {
    this.user.isLogging  = logging
}

get userIsLogging() {
    return this.user.isLogging
}

}



  [1]: https://i.ibb.co/0CBSZ5v/Screenshot-from-2019-04-19-19-07-44.png

标签: reactjsredux

解决方案


您使用减速器错误。

1-当你创建一个状态时,确保它只是一个没有任何方法的原始类型。

2- reducer 负责在任何操作上创建新状态。但你只是返回初始状态。你应该有类似的东西

case USER.LOGIN_REQUEST:
        console.log(state)
        initialState.userIsLogging = action.payload
        return {
           ...state,
           userIsLogging: action.payload,
        }

3-您可能想检查 sagas。您不必自己处理所有这些异步逻辑


推荐阅读