【发布时间】:2022-01-11 05:33:36
【问题描述】:
我一直在学习关于 react 的在线课程,但它有点过时了,我一直在努力通过所有课程来理解在应用新语法而不是视频中显示的语法时解释的概念。我总是或多或少地管理,但现在我被卡住了,因为在添加反应路由器 dom Web 应用程序后,我的页面不再呈现。没有显示错误或警告,无论我看多少,我似乎都找不到错误。我的主要现在看起来像这样:
import React from 'react';
import Header from './header';
import MyPlacesList from './myplaceslist.js';
import Footer from './footer';
import CreatePlace from './createPlace.js';
import * as attAPI from '../utils/attractionsAPI';
import { Router, Route } from 'react-router-dom';
class Main extends React.Component{
state = {
attractions: [],
}
componentDidMount(){
attAPI.getAll().then((attractions) => {
this.setState({attractions})
})
}
removePlace = (attraction) => {
this.setState((state) => ({
attractions: state.attractions.filter((attr) => attr.id !== attraction.id)
}))
attAPI.remove(attraction);
}
render(){
return (
<Router>
<Fragment>
<Header titolo = 'My Places' sottotitolo = 'I miei posti preferiti'/>
<Route exact path = '/' render = {() => (
<MyPlacesList attractions = {this.state.attractions}
onRemovePlace = {this.removePlace} />
)}/>
<Route path = '/create' render = {() => (
<CreatePlace />
)}/>
<Footer />
</Fragment>
</Router>
)
}
}
export default Main;
这是标题:
import React from 'react';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Icon from '@mui/material/Icon';
import AddCircleIcon from '@mui/icons-material/AddCircle';
import { Link } from 'react-router-dom';
class Header extends React.Component{
render(){
// return <nav>
// <div className = "nav-wrapper">
// <a href = "#" className = "brand-logo">{this.props.titolo}</a>
// </div>
// </nav>
return <Box sx={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<Typography
variant="h6"
noWrap
component="div"
sx={{ flexGrow: 1, display: { xs: 'none', sm: 'block' } }}
>
{this.props.titolo}
</Typography>
<Link to = '/create'>
<IconButton>
<AddCircleIcon />
</IconButton>
</Link>
</Toolbar>
</AppBar>
</Box>
}
}
export default Header;
在添加反应路由器 dom 之前,我使用状态调用组件 MyPlacesList/CreatePlace(createPlace 仅在我单击按钮时显示)并且它工作得很好,在我尝试使用 <Route> 后出现了问题。我该如何解决这个问题?提前谢谢你!
编辑 - 这也是我的索引页:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Main from './components/main';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<Main/>
</BrowserRouter>, document.getElementById('root'));
【问题讨论】:
-
尝试使用这个
import { BrowserRouter, Route, Link } from "react-router-dom";。来源:v5.reactrouter.com/web/guides/primary-components。尝试阅读您正在使用的版本的文档。 -
我也添加了索引页面,那是我的 BrowserRouter 指令所在的地方!
标签: javascript reactjs