首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从数据库中获取页面后进行重定向

从数据库中获取页面后进行重定向
EN

Stack Overflow用户
提问于 2022-07-21 11:16:09
回答 1查看 37关注 0票数 1

我正在做一个url短程序项目。在这个项目中,我将网页存储到数据库中,并在地址栏中输入url(url将始终有效)重定向到网页。

我试图使用以下代码重定向给定的外部网站

代码语言:javascript
运行
复制
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代码

代码语言:javascript
运行
复制
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更改为:

代码语言:javascript
运行
复制
http://localhost:3000/[object%20Object]

如果我注释掉重定向,我将得到html.中的有效url。

EN

回答 1

Stack Overflow用户

发布于 2022-07-25 16:44:31

只有当路径发生变化时,您才应该执行这些check / api调用。因此,在依赖项中使用useEffect。

代码语言:javascript
运行
复制
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]);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73065221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档