redex 툴킷에서 리듀서와 엑스트라 리듀서의 차이점은 무엇입니까?
2개월 동안 redux 툴킷에 대해 배웠습니다.createSlice갖고 있다reducers그리고.extrareducersdispatch와 dispatch의 상태가 바뀌는 것은 알고 있습니다만, 그 차이를 모르겠습니다.어디에 사용하면 좋을까요?
그reducers속성은 둘 다 작업 생성자 함수를 생성하고 슬라이스 축소기에서 해당 작업에 응답합니다.그extraReducers슬라이스 리듀서의 액션에 응답할 수 있지만 액션크리에이터 기능은 작성하지 않습니다.
를 사용합니다.reducers대부분의 시간.
사용할 수 있습니다.extraReducers다른 곳에서 이미 정의한 액션을 처리할 때 사용합니다.가장 일반적인 예로는 에 대한 응답입니다.createAsyncThunk동작 및 다른 슬라이스의 동작에 응답합니다.
extrareducers사실 같은 거야reducers(다른 슬라이스에서 생성된 액션이나 에 의해 수행된 액션 등) 더 많은 옵션을 처리할 수 있도록 구축되었습니다.createAction또는createAsyncThunk한마디로
레독스로 디스패치할 수 있는 것은 모두 추가할 수 있습니다.
그extrareducers에 있어서의 재산.createSlice함수 또는 객체로 사용할 수 있습니다.
함수 양식에는 다음과 같은 이름의 입력 인수가 있습니다.builder.
예 1:builder.addCase함수는 다른 슬라이스에서 액션을 추가합니다(Typescript type safety).
const {actions,reducer} = createSlice({
name:'users',
reducers:{
......
},
initialState:.... ,
extraReducers:(builder) => {
builder.addCase(authActions.logout, state => {
state.isLoggedIn = false;
});
}
});
그authActions.logout여기 다른 슬라이스의 다른 액션이 있습니다.
다음을 사용하여 작업을 만드는 경우createAsyncThunk("@reduxjs/toolkit"에서 Import한 함수) 로딩, 성공 및 실패 상태를 처리할 수 있습니다.
예 2: 비동기 Thunk로부터의 로드 상태 처리:
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
const {actions,reducer} = createSlice({
name:'users',
reducers:{
......
},
initialState:.... ,
extraReducers: (builder) => {
......
......
builder.addCase(fetchUserById.pending, (state, action) => {
state.loading=true;
state.whoseDataIsLoading = action.payload;
})
}
});
- fetchUserById.pending(비동기 트렁크 로드 상태 처리)
- fetchUserById.rejected(처리 실패 상태)
- fetchUserById.fulfuled(처리 성공 상태)
건축업자는 또한 다음을 받아들인다.addDefaultCase그리고.addMatcher그 안에서addDefaultCase는 기존의 리덕터(툴킷이 없는 리덕터 내의 리덕터)에 의해 사용되는 스위치 스테이트먼트의 디폴트 케이스로서 기능합니다.
addMatcher는 타입 술어 함수와 함께 사용되며, 이 함수는 일부 입력에 특정 타입(여기에서는 액션 타입)이 있다고 추론하기 위해 사용되며, 액션이 특정 타입을 가지도록 한 후 상태가 변화합니다.
예 3:extrareducers오브젝트로서:
const {actions,reducer} = createSlice({
name:'users',
reducers:{
......
},
initialState:.... ,
extraReducers: {
['incrementBy']: (state, action) => {
state.someValue += action.payload
}
}
});
참고 자료:
https://redux-toolkit.js.org/usage/usage-with-typescript#type-safety-with-extrareducers
https://redux-toolkit.js.org/usage/usage-with-typescript#typing-builderaddmatcher
https://redux-toolkit.js.org/api/createReducer#builderadddefaultcase
예를 들어 다음과 같은 두 가지 리듀서가 있다고 가정해 보겠습니다.
const booksSlice = createSlice({
name: "books",
initialState: [],
reducers: {
addBook(state, action) {
// this state is not global state. it is only books slice
state.push(action.payload);
},
resetBooks(state, action) {
// immers assume whatever you return you want your state to be
return [];
},
},});
export const { addBook, resetBooks } = booksSlice.actions;
const authorsSlice = createSlice({
name: "authors",
initialState: [],
reducers: {
addAuthor(state, action) {
state.push(action.payload);
},
resetAuthors(state, action) {
return [];
},
},});
export const { addAuthor, resetAuthors } =authorsSlice.actions;
양쪽 리듀서의 초기 상태는 []입니다.페이지에 「books」리스트와 「Authors」리스트가 표시되고, 양쪽의 상태를 리셋 하는 버튼이 있다고 합니다.
<button onClick={() => handleResetLists()}>
Clear the page
</button>
에 inside inside inside handleResetLists 가지 에 보낼 수 .
const handleReset = () => {
dispatch(resetBooks());
dispatch(resetAuthors());
};
그 나는 알 수 있었다.authorsSlice extraReducers
const authorsSlice = createSlice({
name: "authors",
initialState: [],
reducers: {
addAuthor(state, action) {
state.push(action.payload);
},
// builder tells this slice to watch for additional action types
extraReducers(builder) {
// second argument will update the state
builder.addCase(booksSlice.actions.reset, () => {
return [];
});
},
},
});
★★★★★★★★★★★★의handleResetfunction,만, 이됩니다.
const handleReset = () => {
dispatch(resetBooks());
// I do not need to dispatch this
// dispatch(resetAuthors());
};
에서는, 「」는,authorsSlice booksSlice는 '우리'를 사용하기 때문이다.booksSlice.actions.reset에 inside inside inside extraReducer, 른, 른, 른, 른, 른, 른, 다, 없애면 어떻게 될까요? 왜냐하면 만약 이 액션을 없애버리면bookSlice
import {createAction} from "@reduxjs/toolkit"
// we are gonna dispatch this
export const resetAction=createAction("lists/reset")
양쪽 슬라이서 안에 이 extraReducer를 추가합니다.
extraReducers(builder) {
builder.addCase(resetAction, (state, action) => {
state = [];
});
},
페이지 안쪽에
import {resetAction} from "./store/actions"
const handleReset = () => {
dispatch(reset());
// I do not need to dispatch this
// dispatch(resetAction());
};
리듀서로 되어야 할 를 합니다.reducers.
이 복수의는, 「」를 해 주세요.extraReducers.
언급URL : https://stackoverflow.com/questions/66425645/what-is-difference-between-reducers-and-extrareducers-in-redux-toolkit
'programing' 카테고리의 다른 글
| 농담 모의 반응 컨텍스트 (0) | 2023.03.05 |
|---|---|
| 문자열을 int64 유형의 Go 값으로 이동 해제할 수 없습니다. (0) | 2023.03.05 |
| Plask에 JSON을 보내는 중, request.args vs request.형태 (0) | 2023.03.05 |
| MAX(날짜)로 그룹화 (0) | 2023.03.05 |
| HTML 대신 javascript에서 필터를 사용하는 방법 (0) | 2023.02.28 |