当使用 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)
});
我该去哪里打电话。提前感谢您提供的任何见解!