我是Redux的新手,在使用Redux时遇到了一些麻烦,所以到目前为止,我所做的可能是错误的,但请耐心等待。总而言之,我希望我的应用程序有一个非常简单的redux状态,只有两个键,"user“和”want“。我设置所有内容的方法是将状态默认为"user:{user: null}“和”have:{landing: true}“。我想知道为什么它被复制成这样,而不只是"user: null“和"landing: true"?
我的减速器:
const initialUserState = {
user: null
};
const initialUiState = {
landing: true
};
export function userReducer(state, action){
if (typeof state === "undefined"){
return initialUserState;
}
switch(action.type){
case SIGN_IN:
return {...state, user: action.userName};
case SIGN_OUT:
return {...state, user: null};
default:
return state;
}
}
export function uiReducer(state, action){
if (typeof state === "undefined"){
return initialUiState;
}
switch(action.type){
case LANDING:
return {...state, landing: true};
case NOT_LANDING:
return {...state, landing: false};
default:
return state;
}
}
以及减速机的组合:
import {userReducer, uiReducer} from "./reducers";
import {combineReducers} from "redux";
export default combineReducers({
user: userReducer,
landing: uiReducer
});
同样,我只希望看到"user: null“和"landing: true",但我在连接中包装的组件中通过控制台注销了状态,我看到了"user:{user: null}”和"landing:{landing: true}“。
发布于 2019-06-11 03:25:23
状态中的第一个层次结构级别由combineReducers
调用中的reducers的名称定义。这对于分离每个单个reducer负责的子状态是必要的。然后,第一层次结构级别内的状态结构完全由相应的缩减程序定义。
在您的示例中,如果您确实希望管理单个值,则可以按如下方式定义缩减程序:
const initialUserState = null;
export function userReducer(state, action){
if (typeof state === "undefined"){
return initialUserState;
}
switch(action.type){
case SIGN_IN:
return action.userName;
case SIGN_OUT:
return null;
default:
return state;
}
}
uiReducer
也是如此。但是,如果您将来需要添加更多的属性,这将是相当不常见的,并且不能很好地扩展。
https://stackoverflow.com/questions/56532082
复制相似问题