React Router Dom不识别useHistory钩子,我该如何修复这个问题?

huangapple go评论61阅读模式
英文:

React Router Dom not recognizing useHistory hook, how do I fix this?

问题

Here's the translated code without addressing the specific issues you mentioned:

import { Button } from "@chakra-ui/button";
import { FormControl, FormLabel } from "@chakra-ui/form-control";
import { Input, InputGroup, InputRightElement } from "@chakra-ui/input";
import { VStack } from "@chakra-ui/layout";
import { useToast } from "@chakra-ui/toast";
import axios from "axios";
import { useState } from "react";
import { useHistory } from "react-router-dom";

const Signup = () => {
  const [show, setShow] = useState(false);
  const handleClick = () => setShow(!show);
  const toast = useToast();
  const history = useHistory();

  const [name, setName] = useState();
  const [email, setEmail] = useState();
  const [confirmpassword, setConfirmpassword] = useState();
  const [password, setPassword] = useState();
  const [pic, setPic] = useState();
  const [picLoading, setPicLoading] = useState(false);

  const submitHandler = async () => {
    setPicLoading(true);
    if (!name || !email || !password || !confirmpassword) {
      toast({
        title: "Please Fill all the Fields",
        status: "warning",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      setPicLoading(false);
      return;
    }
    if (password !== confirmpassword) {
      toast({
        title: "Passwords Do Not Match",
        status: "warning",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      return;
    }
    console.log(name, email, password, pic);
    try {
      const config = {
        headers: {
          "Content-type": "application/json",
        },
      };
      const { data } = await axios.post(
        "/api/user",
        {
          name,
          email,
          password,
          pic,
        },
        config
      );
      console.log(data);
      toast({
        title: "Registration Successful",
        status: "success",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      localStorage.setItem("userInfo", JSON.stringify(data));
      setPicLoading(false);
      history.push("/chats");
    } catch (error) {
      toast({
        title: "Error Occurred!",
        description: error.response.data.message,
        status: "error",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      setPicLoading(false);
    }
  };

  const postDetails = (pics) => {
    setPicLoading(true);
    if (pics === undefined) {
      toast({
        title: "Please Select an Image!",
        status: "warning",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      return;
    }
    console.log(pics);
    if (pics.type === "image/jpeg" || pics.type === "image/png") {
      const data = new FormData();
      data.append("file", pics);
      data.append("upload_preset", "chat-app");
      data.append("cloud_name", "piyushproj");
      fetch("https://api.cloudinary.com/v1_1/piyushproj/image/upload", {
        method: "post",
        body: data,
      })
        .then((res) => res.json())
        .then((data) => {
          setPic(data.url.toString());
          console.log(data.url.toString());
          setPicLoading(false);
        })
        .catch((err) => {
          console.log(err);
          setPicLoading(false);
        });
    } else {
      toast({
        title: "Please Select an Image!",
        status: "warning",
        duration: 5000,
        isClosable: true,
        position: "bottom",
      });
      setPicLoading(false);
    }
  };

  return (
    <VStack spacing="5px">
      <FormControl id="first-name" isRequired>
        <FormLabel>Name</FormLabel>
        <Input
          placeholder="Enter Your Name"
          onChange={(e) => setName(e.target.value)}
        />
      </FormControl>
      <FormControl id="email" isRequired>
        <FormLabel>Email Address</FormLabel>
        <Input
          type="email"
          placeholder="Enter Your Email Address"
          onChange={(e) => setEmail(e.target.value)}
        />
      </FormControl>
      <FormControl id="password" isRequired>
        <FormLabel>Password</FormLabel>
        <InputGroup size="md">
          <Input
            type={show ? "text" : "password"}
            placeholder="Enter Password"
            onChange={(e) => setPassword(e.target.value)}
          />
          <InputRightElement width="4.5rem">
            <Button h="1.75rem" size="sm" onClick={handleClick}>
              {show ? "Hide" : "Show"}
            </Button>
          </InputRightElement>
        </InputGroup>
      </FormControl>
      <FormControl id="password" isRequired>
        <FormLabel>Confirm Password</FormLabel>
        <InputGroup size="md">
          <Input
            type={show ? "text" : "password"}
            placeholder="Confirm password"
            onChange={(e) => setConfirmpassword(e.target.value)}
          />
          <InputRightElement width="4.5rem">
            <Button h="1.75rem" size="sm" onClick={handleClick}>
              {show ? "Hide" : "Show"}
            </Button>
          </InputRightElement>
        </InputGroup>
      </FormControl>
      <FormControl id="pic">
        <FormLabel>Upload your Picture</FormLabel>
        <Input
          type="file"
          p={1.5}
          accept="image/*"
          onChange={(e) => postDetails(e.target.files[0])}
        />
      </FormControl>
      <Button
        colorScheme="blue"
        width="100%"
        style={{ marginTop: 15 }}
        onClick={submitHandler}
        isLoading={picLoading}
      >
        Sign Up
      </Button>
    </VStack>
  );
};

export default Signup;

Please note that the translation provided above only covers the code portion and does not address the specific issues you mentioned. You may need to debug and resolve the useHistory issue separately.

英文:
import { Button } from &quot;@chakra-ui/button&quot;;
import { FormControl, FormLabel } from &quot;@chakra-ui/form-control&quot;;
import { Input, InputGroup, InputRightElement } from &quot;@chakra-ui/input&quot;;
import { VStack } from &quot;@chakra-ui/layout&quot;;
import { useToast } from &quot;@chakra-ui/toast&quot;;
import axios from &quot;axios&quot;;
import { useState } from &quot;react&quot;;
import {useHistory}  from &quot;react-router-dom&quot;;
const Signup = () =&gt; {
const [show, setShow] = useState(false);
const handleClick = () =&gt; setShow(!show);
const toast = useToast();
const history = useHistory();
const [name, setName] = useState();
const [email, setEmail] = useState();
const [confirmpassword, setConfirmpassword] = useState();
const [password, setPassword] = useState();
const [pic, setPic] = useState();
const [picLoading, setPicLoading] = useState(false);
const submitHandler = async () =&gt; {
setPicLoading(true);
if (!name || !email || !password || !confirmpassword) {
toast({
title: &quot;Please Fill all the Feilds&quot;,
status: &quot;warning&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
setPicLoading(false);
return;
}
if (password !== confirmpassword) {
toast({
title: &quot;Passwords Do Not Match&quot;,
status: &quot;warning&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
return;
}
console.log(name, email, password, pic);
try {
const config = {
headers: {
&quot;Content-type&quot;: &quot;application/json&quot;,
},
};
const { data } = await axios.post(
&quot;/api/user&quot;,
{
name,
email,
password,
pic,
},
config
);
console.log(data);
toast({
title: &quot;Registration Successful&quot;,
status: &quot;success&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
localStorage.setItem(&quot;userInfo&quot;, JSON.stringify(data));
setPicLoading(false);
history.push(&quot;/chats&quot;);
} catch (error) {
toast({
title: &quot;Error Occured!&quot;,
description: error.response.data.message,
status: &quot;error&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
setPicLoading(false);
}
};
const postDetails = (pics) =&gt; {
setPicLoading(true);
if (pics === undefined) {
toast({
title: &quot;Please Select an Image!&quot;,
status: &quot;warning&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
return;
}
console.log(pics);
if (pics.type === &quot;image/jpeg&quot; || pics.type === &quot;image/png&quot;) {
const data = new FormData();
data.append(&quot;file&quot;, pics);
data.append(&quot;upload_preset&quot;, &quot;chat-app&quot;);
data.append(&quot;cloud_name&quot;, &quot;piyushproj&quot;);
fetch(&quot;https://api.cloudinary.com/v1_1/piyushproj/image/upload&quot;, {
method: &quot;post&quot;,
body: data,
})
.then((res) =&gt; res.json())
.then((data) =&gt; {
setPic(data.url.toString());
console.log(data.url.toString());
setPicLoading(false);
})
.catch((err) =&gt; {
console.log(err);
setPicLoading(false);
});
} else {
toast({
title: &quot;Please Select an Image!&quot;,
status: &quot;warning&quot;,
duration: 5000,
isClosable: true,
position: &quot;bottom&quot;,
});
setPicLoading(false);
}
};
return (
&lt;VStack spacing=&quot;5px&quot;&gt;
&lt;FormControl id=&quot;first-name&quot; isRequired&gt;
&lt;FormLabel&gt;Name&lt;/FormLabel&gt;
&lt;Input
placeholder=&quot;Enter Your Name&quot;
onChange={(e) =&gt; setName(e.target.value)}
/&gt;
&lt;/FormControl&gt;
&lt;FormControl id=&quot;email&quot; isRequired&gt;
&lt;FormLabel&gt;Email Address&lt;/FormLabel&gt;
&lt;Input
type=&quot;email&quot;
placeholder=&quot;Enter Your Email Address&quot;
onChange={(e) =&gt; setEmail(e.target.value)}
/&gt;
&lt;/FormControl&gt;
&lt;FormControl id=&quot;password&quot; isRequired&gt;
&lt;FormLabel&gt;Password&lt;/FormLabel&gt;
&lt;InputGroup size=&quot;md&quot;&gt;
&lt;Input
type={show ? &quot;text&quot; : &quot;password&quot;}
placeholder=&quot;Enter Password&quot;
onChange={(e) =&gt; setPassword(e.target.value)}
/&gt;
&lt;InputRightElement width=&quot;4.5rem&quot;&gt;
&lt;Button h=&quot;1.75rem&quot; size=&quot;sm&quot; onClick={handleClick}&gt;
{show ? &quot;Hide&quot; : &quot;Show&quot;}
&lt;/Button&gt;
&lt;/InputRightElement&gt;
&lt;/InputGroup&gt;
&lt;/FormControl&gt;
&lt;FormControl id=&quot;password&quot; isRequired&gt;
&lt;FormLabel&gt;Confirm Password&lt;/FormLabel&gt;
&lt;InputGroup size=&quot;md&quot;&gt;
&lt;Input
type={show ? &quot;text&quot; : &quot;password&quot;}
placeholder=&quot;Confirm password&quot;
onChange={(e) =&gt; setConfirmpassword(e.target.value)}
/&gt;
&lt;InputRightElement width=&quot;4.5rem&quot;&gt;
&lt;Button h=&quot;1.75rem&quot; size=&quot;sm&quot; onClick={handleClick}&gt;
{show ? &quot;Hide&quot; : &quot;Show&quot;}
&lt;/Button&gt;
&lt;/InputRightElement&gt;
&lt;/InputGroup&gt;
&lt;/FormControl&gt;
&lt;FormControl id=&quot;pic&quot;&gt;
&lt;FormLabel&gt;Upload your Picture&lt;/FormLabel&gt;
&lt;Input
type=&quot;file&quot;
p={1.5}
accept=&quot;image/*&quot;
onChange={(e) =&gt; postDetails(e.target.files[0])}
/&gt;
&lt;/FormControl&gt;
&lt;Button
colorScheme=&quot;blue&quot;
width=&quot;100%&quot;
style={{ marginTop: 15 }}
onClick={submitHandler}
isLoading={picLoading}
&gt;
Sign Up
&lt;/Button&gt;
&lt;/VStack&gt;
);
};
export default Signup;
[the error occured is in this image](https://i.stack.imgur.com/E1M0p.png)

in the above code there are syntactical errors and i have installed react-router-dom using command npm i react-router-dom and still i am receiving error like useHistory is not found .And if are import useHistory as import {useHistory} from 'react' it shows no erro in vs code conole but i am having error in browser console and unable to see my frontend only blank page is appearing after reload

i am expecting a login page with no errors and data to be transfered to my mongodb database

答案1

得分: 0

"useHistory"的使用已被弃用。您可以使用"useNavigate"如下:

import { useNavigate } from "react-router-dom";

const MyComponent = () => {
  const navigate = useNavigate();

  // 使用 navigate("/chats") 导航到"/chats"路由

  return (
    // 您组件的JSX
  );
};
英文:

The usage of "useHistory" is deprecated. Instead, you can use "useNavigate" as follows:

import { useNavigate } from &quot;react-router-dom&quot;;
const MyComponent = () =&gt; {
const navigate = useNavigate();
// Use navigate(&quot;/chats&quot;) to navigate to the &quot;/chats&quot; route
return (
// Your component&#39;s JSX
);
};

huangapple
  • 本文由 发表于 2023年5月25日 19:45:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331913.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定