Redux官网学习知识点(day2):useSelector、useDispatch、createAsyncThunk、createSlice

  1. useSelector
  2. useDispatch
  3. createAsyncThunk
  4. 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;
      });
  },
});
上一篇:设计模式,策略模式,c++实现


下一篇:妙用AccessibilityService黑科技实现微信自动加好友拉人进群聊