gpt4 book ai didi

reactjs - 更改后的路径不起作用

转载 作者:行者123 更新时间:2023-12-05 06:54:03 24 4
gpt4 key购买 nike

我想延长<Route> react-router-dom 的组成部分|所以它会在 path 之前添加一些值属性(property)。它看起来像这样:

export default function MyRoute({path, ...rest}) {
const newpath = '/app' + path;
return <Route path={newpath} {...rest} />
}

我想像这样使用它:

<MyRoute path="/login" component={Login} />

所以它应该在幕后呈现:

<Route path="/app/login" component={Login} />

当我去 /app/login url 它不加载。 <Login />仍然只出现在 /login 上.

我在这里做错了什么?

编辑

直接在<Switch>里面使用是不行的:

<Switch>
<MyRoute path="/login" />
</Switch>

但在移动到另一个组件时有效:

<Switch>
<Routes />
</Switch>

和路由:

<>
<MyRoute path="/login" />
</>

最佳答案

我最终使用了以下代码:

index.html

<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

<!-- Below we can set subpage containing React app -->
<script>window.react_app_url = '/my-app-page'</script>

<div id="root"></div>
</body>
</html>

自定义 <MyRoute>应该覆盖所有 path要包含的属性 react_app_url在 index.html 中定义。前任。 <MyRoute path="/home" />应该变成 <Route path="/my-app-page/home" /> .

MyRoute.js

import React from 'react';

export default function MyRoute({path, ...rest}) {
let appUrl = '';
if(window.hasOwnProperty('react_app_url')) {
appUrl = window.react_app_url;
}

if( Array.isArray(path) ) {
const paths = path.map(singlepath=>`${appUrl}${singlepath}`);
path = paths;
} else {
path = appUrl + path;
}
return <Route path={path} {...rest} />;
}

App.js我们现在可以使用自定义 <Routes>里面<Switch>和所有 paths将被替换为,ex。 /home/my-app-page/home .

App.js

import React from 'react';

import {BrowserRouter, Switch} from 'react-router-dom';
import MyRoute from './MyRoute';

export default function App() {
return (
<BrowserRouter>
<Switch>
<>
<MyRoute path="/home" component={Home} />
<MyRoute path="/about" component={About} />
<MyRoute path="/contact" component={Contact} />
</>
</Switch>
</BrowserRouter>
);
}

关于reactjs - <PrivateRoute> 更改后的路径不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65639445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com