我不知道哪里有麻烦。但当我尝试登录,它不想导航到下一个页面,并停留在模式登录。请告诉我我的密码有什么问题吗?
let navigate = useNavigate();
const dispatch = useContext(UserContext);
const state = useContext(UserContext);
// console.log(state);
const [form, setForm] = useState({
  email: "",
  password: "",
});
const { email, password } = form;
const handleChange = (e) => {
  setForm({
    ...form,
    [e.target.name]: e.target.value,
  });
};
const handleSubmitLog = async (e) => {
  try {
    e.preventDefault();
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };
    const body = JSON.stringify(form);
    const response = await API.post("/login", body, config);
    console.log(response.data);
    if (response?.status == 200) {
      dispatch({
        type: "LOGIN_SUCCESS",
        payload: response.data.data,
      });
      
      if (response.data.data.status == "admin") {
        navigate('/admin')
      } else {
        navigate('/userid')
      }
    }
  } catch (error) {
    console.log(error);
  }
}这是控制台的响应,我不知道为什么这个调度不能正常工作。
{
    "status": "Success",
    "data": {
        "users": {
            "name": "mr.x",
            "email": "mr.x@mail.com",
            "token": "asfsa"
        }
    }
}
TypeError: dispatch is not a function
    at handleSubmitLog (header.js:59:1)这是userContext文件中的身体。请检查一下,告诉我我的代码是否错了。
export const UserContext = createContext();
const initialState = {
  isLogin: false,
  user: {},
};
const reducer = (state, action) => {
  const { type, payload } = action;
  switch (type) {
    case "USER_SUCCESS":
    case "LOGIN_SUCCESS":
      localStorage.setItem("token", payload.token)
      return {
        isLogin: true,
        user: payload,
      };
    case "AUTH_ERROR":
    case "LOGOUT":
      localStorage.removeItem("token")
      return {
        isLogin: false,
        user: {},
      };
    default:
      throw new Error();
  }
};
export const UserContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <UserContext.Provider value={[state, dispatch]}>
      {children}
    </UserContext.Provider>
  );
};发布于 2022-02-28 20:47:52
UserContext值是一个数组[state, dispatch]
<UserContext.Provider value={[state, dispatch]}>
  {children}
</UserContext.Provider>但是组件没有正确地访问上下文值:
const dispatch = useContext(UserContext);
const state = useContext(UserContext);这里,dispatch 和 state都是[state, dispatch]的相同的上下文值。
您只需要一次useContext(UserContext)访问,以下任一项:
userContext = useContext(UserContext);. // userContext;状态对象/值// userContext1;调度函数userContext1({ type:"LOGIN_SUCCESS",有效载荷: response.data.data,});
state和dispatch值:const状态,调度= useContext(UserContext);分派({ type:"LOGIN_SUCCESS",有效载荷: response.data.data,});
发布于 2022-02-27 02:46:19
试试这个:
  const { state, dispatch } = useContext(AppContext)https://stackoverflow.com/questions/71281652
复制相似问题