【问题标题】:React using context, and useRef not acting as expected使用上下文做出反应,并且 useRef 未按预期运行
【发布时间】:2022-12-11 06:17:38
【问题描述】:

因此,我使用 useContext 和 useRef 来为一个简单的博客应用程序存储用户信息。让我给你看代码,在第一个 sn-p 之后我会解释这个问题:

登录.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 我得到 user: 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>
  );
};

Reducer.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;

我也有一个基本的 Actions 设置,但我只是在做

dispatch({ type: "LOGIN_SUCCESS", payload: res.data }) 

代替

dispatch(LoginSuccess(res.data))

请注意,我边走边学,而且我大大感谢帮助。

【问题讨论】:

  • 输入的实际值在 ref.current 中不可用,它在 ref.current.value 中可用。

标签: node.js reactjs react-context use-ref


【解决方案1】:

如果指向 ref.current,请更改 handleSubmit 函数 try catch 块、用户名和密码,对于 value,它应该指向 ref.current.value

try {
      const res = await axios.post("/auth/login", {
        username: userRef.current.value,
        password: passwordRef.current.value, 
      });
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "LOGIN_FAILURE" });
    }

【讨论】:

  • 抱歉抱歉,这就是我最初拥有它的方式 ref.current.value 但我在乱搞,忘了把它放回去。我将再次解决这个问题---会让你知道它是怎么回事!
  • 是的,我仍然有同样的问题。
  • 我让它工作 :) 不确定为什么它最初不工作。服务器只是响应有点慢。谢谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 2022-07-18
  • 2022-12-03
  • 1970-01-01
  • 2022-01-06
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多