reactjs - 类对象在减速器中无法正常工作
问题描述
我有一个用户模型(es6 类),我正在使用新键盘创建一个对象,并将其传递给我的 userReducer 函数的 initialState。如何根据操作更新模型。
例如,如果我尝试发送一个动作来更改isLogging
userModel 中的值,那么记录器中的 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
解决方案
您使用减速器错误。
1-当你创建一个状态时,确保它只是一个没有任何方法的原始类型。
2- reducer 负责在任何操作上创建新状态。但你只是返回初始状态。你应该有类似的东西
case USER.LOGIN_REQUEST:
console.log(state)
initialState.userIsLogging = action.payload
return {
...state,
userIsLogging: action.payload,
}
3-您可能想检查 sagas。您不必自己处理所有这些异步逻辑
推荐阅读
- ruby-on-rails - Ruby on Rails - 订单不与 distinct.pluck 一起使用
- linux - 安装 OpenCV 错误 libtiff5-dev : Depends: liblzma-dev 但它不会被安装
- list - Dart 将项目列表组合成不同的数据结构?
- mysql - 如何在 Quarkus for Liquibase 中定义两个不同的数据库用户
- javascript - 过滤包含特定值的数组中的每个字符串
- ruby-on-rails - 是否可以指定链式范围查询的顺序
- c# - 如何在 ASP Web Api 中将多个键传递给数组?
- javascript - 如何在鼠标位置跟踪的父元素内移动子元素
- git - 如何更新 Github 克隆存储库?
- ruby-on-rails - 调用切片!使用 map / symbol_to_proc 语法