我对Redux非常陌生,据我所知,应该为每种类型的对象创建一个还原器。例如,对于用户交互,应该创建一个用户缩减器。,我的问题是:,您如何处理为了不同目的而需要对象的情况?
场景:设想有一个返回当前用户的用户缩减器。这个用户在整个应用程序中是必需的,并且需要每个页面上的通用控件。
现在,当您需要加载用于不同目的的另一个用户时,会发生什么情况。例如配置文件页面:加载用户以显示信息。
在这种情况下,如果使用用户还原器,就会出现冲突。在Redux中处理这个问题的正确方法是什么?如果需要创建不同的还原器,新减速器的命名约定是什么?
发布于 2016-06-19 20:51:44
首先,你提到:
加载当前用户的用户还原器。
我不知道是否正确,但如果这意味着要从还原器中获取当前用户(例如,从API ),这是一个错误的方法。
减速器被设计为纯函数。您可以使用相同的参数多次调用它们,它们总是返回相同的预期状态。
这样的副作用应该由行动创造者来处理,例如:
actions/user.js
export const FETCH_ME = 'FETCH_ME'
export const FETCH_ME_SUCCESS = 'FETCH_ME_SUCCESS'
// it's using redux-thunk (withExtraArgument: api) module to make an async action creator
export const fetchMe = () => (dispatch, getState, api) => {
dispatch({ type: FETCH_ME })
return api.get('/users/me').then(({ data }) => {
dispatch({ type: FETCH_ME_SUCCESS, data })
return data
})
}在还原器中,您可以简单地获取数据并设置一个新的状态(请注意,如果您用相同的数据多次发送操作,状态将始终相同)。
reducers/user.js
import { FETCH_ME, FETCH_ME_SUCCESS } from '../actions/user'
const initialState = {
item: null,
loading: false
}
export const userReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_ME:
return {
...state,
loading: true
}
case FETCH_ME_SUCCESS:
return {
...state,
loading: false,
item: action.data
}
default:
return state
}
}现在,对于您的场景:
现在,当您需要加载用于不同目的的另一个用户时,会发生什么情况。例如配置文件页面:加载用户以显示信息。
您只需为此编写另一个操作创建者:
actions/user.js
export const FETCH_ME = 'FETCH_ME'
export const FETCH_ME_SUCCESS = 'FETCH_ME_SUCCESS'
export const FETCH_USER = 'FETCH_USER'
export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS'
export const fetchMe = () => (dispatch, getState, api) => {
dispatch({ type: FETCH_ME })
return api.get('/users/me').then(({ data }) => {
dispatch({ type: FETCH_ME_SUCCESS, data })
return data
})
}
export const fetchUser = (id) => (dispatch, getState, api) => {
dispatch({ type: FETCH_USER })
return api.get(`/users/${id}`).then(({ data }) => {
dispatch({ type: FETCH_USER_SUCCESS, data })
return data
})
}然后你调整你的减速器来管理更多的设备:
reducers/user.js
import { combineReducers } from 'redux'
import { FETCH_ME, FETCH_ME_SUCCESS, FETCH_USER, FETCH_USER_SUCCESS } from '../actions/user'
const initialState = {
item: null,
loading: false
}
const meReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_ME:
case FETCH_ME_SUCCESS:
return userReducer(state, action)
default:
return state
}
}
const activeReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_USER:
case FETCH_USER_SUCCESS:
return userReducer(state, action)
default:
return state
}
}
const userReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_USER:
case FETCH_ME:
return {
...state,
loading: true
}
case FETCH_USER_SUCCESS:
case FETCH_ME_SUCCESS:
return {
...state,
loading: false,
item: action.data
}
default:
return state
}
}
export default combineReducers({
activeUser: activeReducer,
me: meReducer
})您的最终用户状态应该如下所示:
{
me: {
item: null,
loading: false
},
active: {
item: null,
loading: false
}
}https://stackoverflow.com/questions/37909518
复制相似问题