因此,我将使用useContext沿着useRef来存储一个简单的blog应用程序的用户信息。让我向您展示代码,在第一个片段之后,我将解释这个问题:
登录名.jsx
import "./login.css";
import { Link } from "react-router-dom";
import { useContext, useRef } from "react";
import { Context } from "../../../context/Context";
import axios from "axios";
export default function Login() {
const userRef = useRef();
const passwordRef = useRef();
const { user, dispatch, isFetching } = useContext(Context);
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/login", {
username: userRef.current,
password: passwordRef.current,
});
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE" });
}
};
///////////////////console.log('user: '+ user)
return (
<div className="login">
<span className="login--title">Login</span>
<form className="login--form" onSubmit={handleSubmit}>
<label>Username</label>
<input
type="text"
className="login--input"
placeholder="Enter your username..."
ref={userRef}
/>
<label>Password</label>
<input
type="password"
className="login--input"
placeholder="Enter your password..."
ref={passwordRef}
/>
<button className="login--btn" type="submit">
Login
</button>
</form>
<button className="login--register-btn">
<Link className="link" to="/register">
Register
</Link>
</button>
</div>
);
}
**现在使用用户的console.log,我得到用户:null,而不是预期的用户对象?**以下是我当前上下文设置的其余部分。
上下文.js
import { createContext, useReducer } from "react";
import Reducer from "./Reducer";
const INITIAL_STATE = {
user: null,
isFetching: false,
error: false,
};
export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
return (
<Context.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch,
}}
>
{children}
</Context.Provider>
);
};
减速器.Js
const Reducer = (state, action) => {
switch (action.type) {
case "LOGIN_START":
return {
user: null,
isFetching: true,
error: false,
};
case "LOGIN_SUCCESS":
return {
user: action.payload,
isFetching: false,
error: false,
};
case "LOGIN_FAILURE":
return {
user: null,
isFetching: false,
error: true,
};
case "UPDATE_START":
return {
...state,
isFetching: true,
};
case "UPDATE_SUCCESS":
return {
user: action.payload,
isFetching: false,
error: false,
};
case "UPDATE_FAILURE":
return {
user: state.user,
isFetching: false,
error: true,
};
case "LOGOUT":
return {
user: null,
isFetching: false,
error: false,
};
default:
return state;
}
};
export default Reducer;
我也有一个基本的操作设置,但我只是
dispatch({ type: "LOGIN_SUCCESS", payload: res.data })
代替
dispatch(LoginSuccess(res.data))
请注意,我是边走边学,我非常感谢你的帮助。
1条答案
按热度按时间velaa5lx1#
如果指向ref.current,请更改handleSubmit函数try catch块、用户名和密码,对于值,它应指向ref.current.value