반응형
내포 환원기
내포된 환원기를 다음 구조와 결합할 수 있는가?
import 'user' from ...
import 'organisation' from ...
import 'auth' from ...
// ...
export default combineReducers({
auth: {
combineReducers({
user,
organisation,
}),
auth,
},
posts,
pages,
widgets,
// .. more state here
});
국가가 구조를 갖는 경우:
{
auth: {
user: {
firstName: 'Foo',
lastName: 'bar',
}
organisation: {
name: 'Foo Bar Co.'
phone: '1800-123-123',
},
token: 123123123,
cypher: '256',
someKey: 123,
}
}
어디?auth
환원기의 구조:
{
token: 123123123,
cypher: '256',
someKey: 123,
}
그럼 스프레드 오퍼레이터가 편리한가? ...auth
확실하지 않은:-()
다음을 사용하여 중첩된 환원기를 결합해도 완벽히 괜찮다.combineReducers
그러나 정말 편리한 또 다른 패턴이 있다: 중첩 환원기.
const initialState = {
user: null,
organisation: null,
token: null,
cypher: null,
someKey: null,
}
function authReducer(state = initialState, action) {
switch (action.type) {
case SET_ORGANISATION:
return {...state, organisation: organisationReducer(state.organisation, action)}
case SET_USER:
return {...state, user: userReducer(state.user, action)}
case SET_TOKEN:
return {...state, token: action.token}
default:
return state
}
}
위의 예에서,authReducer
에 조치를 전달할 수 있다.organisationReducer
그리고userReducer
상태 일부를 업데이트하는 것.
@Florent가 준 아주 좋은 대답에 대해 좀 더 자세히 설명하고, 여러분의 뿌리 환원기를 또한 복합 환원기인 환원기와 결합시킴으로써 중첩 환원기를 얻기 위해 여러분의 앱을 약간 다르게 구성할 수 있다는 것을 지적하고 싶다.
예를 들어,
// src/reducers/index.js
import { combineReducers } from "redux";
import auth from "./auth";
import posts from "./posts";
import pages from "./pages";
import widgets from "./widgets";
export default combineReducers({
auth,
posts,
pages,
widgets
});
// src/reducers/auth/index.js
// note src/reducers/auth is instead a directory
import { combineReducers } from "redux";
import organization from "./organization";
import user from "./user";
import security from "./security";
export default combineReducers({
user,
organization,
security
});
이것은 국가 구조의 약간 다른 것을 가정한다.대신 다음과 같이 하십시오.
{
auth: {
user: {
firstName: 'Foo',
lastName: 'bar',
}
organisation: {
name: 'Foo Bar Co.'
phone: '1800-123-123',
},
security: {
token: 123123123,
cypher: '256',
someKey: 123
}
},
...
}
@Florent의 접근방식은 주 구조를 바꿀 수 없다면 더 나을 것 같다.
@florent의 대답에 영감을 받아, 나는 너도 이것을 시도해 볼 수 있다는 것을 알게 되었다.꼭 그의 대답보다 낫다고는 할 수 없지만, 좀 더 우아하다고 생각한다.
function userReducer(state={}, action) {
switch (action.type) {
case SET_USERNAME:
state.name = action.name;
return state;
default:
return state;
}
}
function authReducer(state = {
token: null,
cypher: null,
someKey: null,
}, action) {
switch (action.type) {
case SET_TOKEN:
return {...state, token: action.token}
default:
// note: since state doesn't have "user",
// so it will return undefined when you access it.
// this will allow you to use default value from actually reducer.
return {...state, user: userReducer(state.user, action)}
}
}
예(참조)attachNestedReducers
야옹야옹)
import { attachNestedReducers } from './utils'
import { profileReducer } from './profile.reducer'
const initialState = { some: 'state' }
const userReducerFn = (state = initialState, action) => {
switch (action.type) {
default:
return state
}
}
export const userReducer = attachNestedReducers(userReducerFn, {
profile: profileReducer,
})
상태 객체
{
some: 'state',
profile: { /* ... */ }
}
여기 함수가 있다.
export function attachNestedReducers(original, reducers) {
const nestedReducerKeys = Object.keys(reducers)
return function combination(state, action) {
const nextState = original(state, action)
let hasChanged = false
const nestedState = {}
for (let i = 0; i < nestedReducerKeys.length; i++) {
const key = nestedReducerKeys[i]
const reducer = reducers[key]
const previousStateForKey = nextState[key]
const nextStateForKey = reducer(previousStateForKey, action)
nestedState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? Object.assign({}, nextState, nestedState) : nextState
}
}
내포 환원기 예제:
import {combineReducers} from 'redux';
export default combineReducers({
[PATH_USER_STATE]: UserReducer,
[PATH_CART_STATE]: combineReducers({
[TOGGLE_CART_DROPDOWN_STATE]: CartDropdownVisibilityReducer,
[CART_ITEMS_STATE]: CartItemsUpdateReducer
})
});
출력:
{
cart: {toggleCartDropdown: {…}, cartItems: {…}}
user: {currentUser: null}
}
참조URL: https://stackoverflow.com/questions/36786244/nested-redux-reducers
반응형
'programing' 카테고리의 다른 글
Python 함수 정의에서 ->는 무엇을 의미하는가? (0) | 2022.04.04 |
---|---|
Windows에서 여러 Python 버전을 실행하는 방법 (0) | 2022.04.04 |
기본 반응에서 경고를 제거하는 방법 (0) | 2022.04.04 |
vuex 작업에서 호출될 때 REST API 호출의 오류를 처리해야 하는 위치 (0) | 2022.04.04 |
Vue 라우터 프로그래밍 방식 네비게이션이 작동하지 않음 (0) | 2022.04.04 |