我正在做一个url短程序项目。在这个项目中,我将网页存储到数据库中,并在地址栏中输入url(url将始终有效)重定向到网页。
我试图使用以下代码重定向给定的外部网站
import { getUrl } from "../apis/api";
import React, { useState } from "react";
const RedirectPage = () => {
const [longUrl, setLongUrl] = useState("");
// const [location,setLocation] = useState("");
const getLink = async (stringUrl) => {
var vlongUrl= await getUrl({stringUrl});
if(vlongUrl){
setLongUrl(vlongUrl);
}
};
var stringUrl= window.location.pathname ;
if(stringUrl.length!==0){
stringUrl = stringUrl.substring(1);
getLink(stringUrl);
}else{
window.location='http://localhost:3000/app'; // Go to not found page
return null;
}
if(longUrl=== "NOT FOUND"){
window.location='http://localhost:3000/notfound'; // Go to not found page
return null;
}else{
window.location.assign(longUrl);
return null;
}
// return (
// <h5>Redirect to <a href= {longUrl} > {longUrl} </a> </h5>
// );
}
export default RedirectPage;但这并不是我想要的那样,我走错了路。
下面是app.js代码
import React from "react";
import { BrowserRouter, Routes, Route} from "react-router-dom";
import AppPage from "./pages/AppPage";
import NotFound from "./pages/NotFound";
import RedirectPage from "./pages/RedirectPage";
function App() {
return (
<>
<BrowserRouter>
<Routes>
{/* <Route exact path="/" element={<AppPage />}></Route> */}
<Route exact path="/app" element={<AppPage />}></Route>
<Route exact path="/notfound" element={<NotFound />}></Route>
<Route exact path="/*" element={<RedirectPage />}></Route>
</Routes>
</BrowserRouter>
</>
);
}
export default App;错误:

Url更改为:
http://localhost:3000/[object%20Object]如果我注释掉重定向,我将得到html.中的有效url。

发布于 2022-07-25 16:44:31
只有当路径发生变化时,您才应该执行这些check / api调用。因此,在依赖项中使用useEffect。
var stringUrl = window.location.pathname ;
useEffect(() => {
if(stringUrl.length!==0) {
stringUrl = stringUrl.substring(1);
getLink(stringUrl);
} else {
window.location='http://localhost:3000/app';
return null;
}
}, [stringUrl]);https://stackoverflow.com/questions/73065221
复制相似问题