reactjs - 如何使用 createSlice 进行 API 调用

标签 reactjs redux react-redux axios redux-toolkit

当我使用 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 来获取 token :

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

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

最佳答案

来自 reactjs subreddit 上的用户 acemark:

FWIW,目前使用 Redux Toolkit 进行异步调用与 Redux 更改无关。

您仍然会使用异步中间件(通常是 redux-thunk)、获取数据并使用结果分派(dispatch)操作。

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())。

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

关于reactjs - 如何使用 createSlice 进行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60290580/

相关文章:

node.js - npm install 出现错误,因为 npm ERR cb() 从未调用过

javascript - ReactDom 未定义

reactjs - Redux 是单向的吗?

reactjs - 使用 Redux hooks 时你需要 action creators 吗?

javascript - React-Router:为什么 <Link> 组件的 onClick 处理程序不会调度我的操作?

javascript - React/Redux 如何访问网络服务中的状态

reactjs - 如何缓存由于ReactlazySuspense而导致的崩溃代码分割?

reactjs - 禁用 Office UI Fabric React DetailsList 中的行

reactjs - 使用 mapDispatchToProps 时,在事件监听器上 react 未定义的 redux 属性

javascript - 如何计算圈复杂度?