1

当使用 redux-tookkit 中的 createSlice 时,我很难理解我在哪里进行异步调用。我尝试按照文档进行操作,但迷失了所有 TypeScript 的内容。(我没有使用 TS)我有一个登录组件:

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)
      });

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

4

1 回答 1

5

来自 reactjs subreddit 上的用户 acemark:

FWIW,目前没有关于使用 Redux Toolkit 进行异步调用的 Redux 更改。

您仍然会使用异步中间件(通常是 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()) 。

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

于 2020-02-20T17:18:57.250 回答