从Redux迁移到Redux工具包

时间:2020-09-18 17:51:40

标签: javascript reactjs redux react-redux redux-toolkit

我正在慢慢地从Redux迁移到Redux工具箱。我还很新,但是我有此登录操作功能。我该如何翻译下面的旧函数,我需要createAsyncThunk才能实现?

export const login = (email, password) => (dispatch) => {
  dispatch(requestLogin());
  firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then((user) => {
      dispatch(responseLogin(user));
    })
    .catch((error) => {
      dispatch(loginError());
    });
};

我的身份验证切片看起来像这样:

const authSlice = createSlice({
  name: "authSlice",
  initialState: {
    isLoggingIn: false,
    isLoggingOut: false,
    isVerifying: false,
    loginError: false,
    logoutError: false,
    isAuthenticated: false,
    user: {},
  },
  reducers: {
    signInWithEmail: (state, action) => {
      const { email, password } = action.payload;
      firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .then((response) => {
          const {
            uid,
            email,
            emailVerified,
            phoneNumber,
            password,
            displayName,
            photoURL,
          } = response.user;
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  extraReducers: {},
});

2 个答案:

答案 0 :(得分:0)

您显示的减速器是非常错误的。 减速器必须从不任何事情异步!

您不需要 createAsyncThunk,但是如果您想要使用它,它将像这样:

export const login = createAsyncThunk(
  'login',
  ({email, password}) => firebase.auth().signInWithEmailAndPassword(email, password)
);

const authSlice = createSlice({
  name: "authSlice",
  initialState: {
    isLoggingIn: false,
    isLoggingOut: false,
    isVerifying: false,
    loginError: false,
    logoutError: false,
    isAuthenticated: false,
    user: {},
  },
  reducers: {
    /* any other state updates here */
  },
  extraReducers: (builder) => {
    builder.addCase(login.pending, (state, action) => {
      // mark something as loading here
    }

    builder.addCase(login.fulfilled, (state, action) => {
      // mark request as complete and save results
    }
  }
});

请注意,createAsyncThunk仅允许将一个参数传递给thunk动作创建者,因此它现在必须是同时具有两个字段的对象,而不是单独的参数。

答案 1 :(得分:0)

让我们创建一个<div *ngFor="let mani of employees"> <div> <p>{{mani?.alphabet}}</p> <p *ngFor="let group of mani?.record"> {{ group?.name }}</p> <hr> </div> </div>

productSlice.js

import { createSlice,createSelector,PayloadAction,createAsyncThunk,} from "@reduxjs/toolkit";

在您的export const fetchProducts = createAsyncThunk( "products/fetchProducts", async (_, thunkAPI) => { try { const response = await fetch(`url`); //where you want to fetch data return await response.json(); } catch (error) { return thunkAPI.rejectWithValue({ error: error.message }); } }); const productsSlice = createSlice({ name: "products", initialState: { products: [], loading: "idle", error: "", }, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchProducts.pending, (state) => { state. products = []; state.loading = "loading"; }); builder.addCase( fetchProducts.fulfilled, (state, { payload }) => { state. products = payload; state.loading = "loaded"; }); builder.addCase( fetchProducts.rejected,(state, action) => { state.loading = "error"; state.error = action.error.message; }); } }); export const selectProducts = createSelector( (state) => ({ products: state.products, loading: state.products.loading, }), (state) => state ); export default productsSlice; 中,将store.js添加到户外减速器中。

然后在组件中使用添加那些代码...我也更喜欢使用钩子

productsSlice: productsSlice.reducer

然后最后一部分像这样在您的主管内部调用这些方法

import { useSelector, useDispatch } from "react-redux";

import { fetchProducts,selectProducts,} from "path/productSlice.js";

最后,您可以在组件中以const dispatch = useDispatch(); const { products } = useSelector(selectProducts); React.useEffect(() => { dispatch(fetchProducts()); }, [dispatch]); 的身份访问数据。