Reduxツールキット
2488 ワード
このポストでは、我々はどのように有用なReduxツールキットを知っているし、それをテーブルに何をpring
-まず、カウンタのアプリのための設定reduxストアを古い方法を
-その後、いくつかのアクションを
その後、ツールキットで同じコードを書きます
ここでは古い方法で私のreduxセットアップです
我々は2つの方法で反応とreduxとシンプルなカウンタを作った
最初の方法はreduxの古い方法を使用し、それは少し混乱し、複雑に設定する最初の
だからここでreduxツールキットは、この問題を解決するために来る
ツールキットの使用の平均理由はredux設定を簡素化することです
ここでは、私は両方の方法についての話をしていません両方の方法を使用しての私は、実際には方法の違いを説明することを好む
希望を楽しむ
//).
-まず、カウンタのアプリのための設定reduxストアを古い方法を
-その後、いくつかのアクションを
その後、ツールキットで同じコードを書きます
ここでは古い方法で私のreduxセットアップです
import { createStore } from "redux";
const initialState = {
counter: 0,
};
// actions
export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const RESET = "RESET";
// counter reducer
const counterReducer = (state = initialState, action) => {
if (action.type === INCREMENT) {
return {
counter: state.counter + 1,
};
}
if (action.type === DECREMENT) {
return {
counter: state.counter - 1,
};
}
if (action.type === RESET) {
return {
counter: 0,
};
}
return state;
};
// ccounter store
const store = createStore(counterReducer);
export default store;
//here we fire diffrent actions
// increment
dispatch({type: INCREMENT})
// decrement
dispatch({type: DECREMENT})
// reset
dispatch({type: RESET})
そして、ここでreduxツールキットと同じ方法です
import { configureStore, createSlice } from "@reduxjs/toolkit";
// initial state
const initialState = {
counter: 0,
};
const counterSlice = createSlice({
name: "counter",
initialState: initialState,
// here we replaced the reducer with this helper function which gives us ability to mutate the state directly
reducers: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
reset(state) {
state.counter = 0;
},
increase(state) {
state.counter = state.counter + action.payload;
},
},
});
// actions to be used from inside the component later to make changes to our state
export const counterActions = counterSlice.actions;
const store = configureStore({
reducer: counterSlice.reducer,
});
export default store;
//increment
counterActions.increment()
//decrement
counterActions.decrement()
//reset
counterActions.reset()
// and if you asking of course you can pass data (payload)
like this
for example as a parameter becase we still have access to the action payload
counterActions.increase(5)
私たちが今まで成し遂げたことを我々は2つの方法で反応とreduxとシンプルなカウンタを作った
最初の方法はreduxの古い方法を使用し、それは少し混乱し、複雑に設定する最初の
だからここでreduxツールキットは、この問題を解決するために来る
ツールキットの使用の平均理由はredux設定を簡素化することです
ここでは、私は両方の方法についての話をしていません両方の方法を使用しての私は、実際には方法の違いを説明することを好む
希望を楽しむ
//).
Reference
この問題について(Reduxツールキット), 我々は、より多くの情報をここで見つけました https://dev.to/mnabawy/redux-toolkit-378fテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol