- useSelector
- useDispatch
- createAsyncThunk
- createSlice
export const selectCount = (state) => state.counter.value;
const count = useSelector(selectCount);
<span className={styles.value}>{count}</span>
import { useSelector, useDispatch } from 'react-redux';
const dispatch = useDispatch();
<button
className={styles.button}
onClick={() => dispatch(incrementByAmount(incrementValue))}
>
Add Amount
</button>
createAsyncThunk方法可以创建一个异步的action,这个方法被执行的时候会有三个
( pending(进行中) fulfilled(成功) rejected(失败))
状态。可以监听状态的改变执行不同的操作
export function fetchCount(amount = 1) {
return new Promise((resolve) =>
setTimeout(() => resolve({ data: amount }), 500)
);
}
export const incrementAsync = createAsyncThunk(
'counter/fetchCount',
async (amount) => {
const response = await fetchCount(amount);
return response.data;
}
);
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
// The `extraReducers` field lets the slice handle actions defined elsewhere,
extraReducers: (builder) => {
builder
.addCase(incrementAsync.pending, (state) => {
state.status = 'loading';
})
.addCase(incrementAsync.fulfilled, (state, action) => {
state.status = 'idle';
state.value += action.payload;
});
},
});