如何使用createSlice进行API调用

时间:2020-02-18 22:50:15

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

我难以理解在redux-tookkit中使用createSlice时在哪里进行异步调用。我尝试关注这些文档,但对所有TypeScript内容一无所知。 (我没有使用TS)我有一个Login组件:

import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import {
  login,
} from "./loginSlice";

import styles from "./Login.module.css";

export const Login = () => {
  const dispatch = useDispatch();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const payload ={
    email: email,
    password: password
  }

  return (
    <form>
      <input
        type="email"
        name="email"
        value={email}
        onChange={e => setEmail(e.target.value)}
      />
      <input
        type="password"
        name="password"
        value="passwordValue"
        onChange={e => setPassword(e.target.value)}
      />
    <button type="button" onClick={() => dispatch(login(payload))}>Submit</button>
    </form>
  );
};


和登录切片:

import { createSlice } from "@reduxjs/toolkit";

export const slice = createSlice({
  name: "login",
  initialState: {
    email: "",
    password: "",
    user: null,
    token: null
  },
  reducers: {
    login: (state, action) => {
      console.log(action.payload.email);
      console.log(action.payload.password);
      const { email, password } = action.payload;
      state.email = email;
      state.password = password;
    },
    logout: state => {
      state.email = "";
      state.password = "";
    }
  }
});

export const { login, logout } = slice.actions;

export default slice.reducer;

并且我想调用我的API来获取令牌:

const authData = {
        username: email,
        password: password
    };
    let url = 'http://127.0.0.1:8080/api-token-auth/';

    axios.post(url, authData)
      .then(res => {

        if (res.status === 200) {
          console.log(res);
          const authCreds = {
            userId: res.data.pk,
            token: res.data.token,
          }
          return authCreds;
        }
        throw res;
      })
      .then(authCreds => {
        dispatch({
            type: "LOGIN",
            payload: authCreds
        })
      })
      .catch(error => {
        setIsSubmitting(false)
        setErrorMessage(error.message || error.statusText)
      });

我该去哪里打电话。在此先感谢您提供的任何见解!

1 个答案:

答案 0 :(得分:4)

在reactjs子reddit上来自用户acemark:

FWIW,目前还没有关于通过Redux Toolkit进行异步调用更改的事情。

您仍将使用异步中间件(通常为redux-thunk),获取数据并根据结果分派操作。

Redux Toolkit的下一版本将包括一个名为createAsyncThunk的帮助程序方法,该方法可以为您执行一些操作分派,但仍是相同的标准过程。

因此,通常,您的切片文件将具有以下内容:

const usersSlice = createSlice({
    name: "users",
    initialState: {
        loading: 'idle',
        users: []
    },
    reducers: {
        usersLoading(state, action) {
            // Use a "state machine" approach for loading state instead of booleans
            if(state.loading === 'idle') {
                state.loading = 'pending'
            }
        },
        usersReceived(state, action) {
            if(state.loading === 'pending') {
                state.loading = 'idle'
                state.users = action.payload
            }
        }
    }
})

const {usersLoading, usersReceived} = usersSlice.actions;

const fetchUsers = () => async dispatch => {
    dispatch(usersLoading());
    const response = await usersAPI.fetchAll()
    dispatch(usersReceived(response.data));

}

然后您将在组件中的某个位置进行dispatch(fetchUsers())。

希望这会为您指明正确的方向!