javascript - 为什么单击链接时我的 React 应用程序会转到自定义 404 未找到页面?
问题描述
我的应用是使用 create-react-app 构建的。一旦我使用该应用程序,一切正常,除非我单击我的投资组合网站(在 MAMP 本地主机上)的链接,它会加载自定义 404 页面而不是 Home 组件。当我从 npm run start 加载应用程序时,它首先落在 Home 组件上,我希望它也在 localhost 和我的实时网站上执行此操作。
我尝试将 package.json 中的“主页”更改为“。” 但它仍然做同样的事情。
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Header from './components/layout/Header';
import NotFound from './components/layout/NotFound';
import Alert from './components/layout/Alert';
import Home from './components/content/Home';
import Movie from './components/content/movies/Movie';
import AlertState from './context/alert/AlertState';
import MovieState from './context/movies/MovieState';
const App = () => {
return (
<MovieState>`enter code here`
<AlertState>
<Router>
<Header text={"Movie App"}/>
<Alert />
<Switch>
<Route path='/' component={Home} />
<Route path='/movie/:title' component={Movie} />
<Route component={NotFound} />
</Switch>
</Router>
</AlertState>
</MovieState>
);
}
export default App
包.json
{
"name": "film_app",
"version": "0.1.0",
"homepage": ".",
"dependencies": {
"axios": "^0.19.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
// Home.js
import React from 'react';
import Search from './Search';
import Movies from './movies/Movies';
const Home = () => {
return (
<>
<Search />
<Movies />
</>
)
}
export default Home
// NotFound.js
import React from 'react';
const NotFound = () => {
return (
<div>
<h1>
Page Not Found
<p className='lead' style={notFoundStyles}>
The page you are looking for does not exist
</p>
</h1>
</div>
)
}
const notFoundStyles = {
textAlign: 'center',
};
export default NotFound
没有错误消息,它只显示 NotFound 组件而不是 Home 组件。
解决方案
将exact
标志添加到您的Home
路线和path='/'
后备路线。
<Switch>
<Route path='/' exact={true} component={Home} />
<Route path='/movie/:title' component={Movie} />
<Route path='/' component={NotFound} />
</Switch>
推荐阅读
- c++ - 使用 bjam 构建提升时没有任何反应
- php - 如何更新图像?
- c# - PingReply 的“RoundTripTime”经常为 0?为什么会这样
- matlab - MATLAB单元测试中的fatalAssertNotError-like-method
- python - 如何识别图像上特定 GPS 坐标对应的像素?
- swift - 无法在 SwiftUI、WatchOS 上使用 TabView
- vba - 如何将多个值放入 1 个变量或多个变量中?
- c - 如何使用openCV提取颜色
- c++ - “顶部”值不会改变我推送或弹出堆栈的次数
- python - 在 login.defs 中使用子进程自动搜索和更改密码老化时遇到问题