猿问

React Router 问题:React 在同一页面中渲染两个组件

我的项目有问题,实际上当用户在我的应用程序中的路由之外输入不同的 url 时,我试图处理 404 页面,但是使用我对 React 和 react-router 的知识只需要放置最后一条路由没有路径和由来自 react-router的Switch包裹的确切路径,但效果不佳,主页同时呈现HomeNotFound组件。

我试图删除路由器内的 Container 组件,但这使得 MenuBar 之后的所有组件都消失了。

我试图将 path='*' 放在最后一个 Route 中有 2 个组件呈现在同一页面中。

我的项目有 3 个主要文件:


1.- Index.js :


import ReactDOM from 'react-dom';

import * as serviceWorker from './serviceWorker';

import ApolloProvider from './ApolloProvider';


import 'semantic-ui-css/semantic.min.css';

import 'animate.css/animate.min.css';

import './App.css';


ReactDOM.render(ApolloProvider, document.getElementById('root'));


serviceWorker.unregister();

2.- ApolloProvider.js(使用带有GraphQL的Apollo):


import React from 'react';

import App from './App';

import ApolloClient from 'apollo-client';

import { InMemoryCache } from 'apollo-cache-inmemory';

import { createHttpLink } from 'apollo-link-http';

import { ApolloProvider } from '@apollo/react-hooks';


const httpLink = createHttpLink({

    uri: 'http://localhost:5000/graphql'

});


const client = new ApolloClient({

    link: httpLink,

    cache: new InMemoryCache()

});


export default (

    <ApolloProvider client={client}>

        <App />

    </ApolloProvider>

);


3.- 最后是 App.js :


import React from 'react';

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import { Container } from 'semantic-ui-react';


import MenuBar from './Components/MenuBar';

import Home from './Pages/Home';

import Login from './Pages/Login';

import Register from './Pages/Register';

import NotFound from './Pages/404';

export default App;


我只需要在用户访问“/”时渲染 Home 组件,但是 react-router 如何同时渲染两个组件很奇怪,如果您发现我错在哪里或解决方案,请告诉我,我会如果我找到解决方案或其他什么,正在发布更新。

ITMISS
浏览 208回答 1
1回答

一只萌萌小番薯

问题得到了解决,这是App.js供将来参考的更新:const App = props => (&nbsp; &nbsp; <Router>&nbsp; &nbsp; &nbsp; &nbsp; <Container>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <MenuBar />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Switch>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/' component={Home} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/login' component={Login} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route exact path='/register' component={Register} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Route path='*' component={NotFound} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </Switch>&nbsp; &nbsp; &nbsp; &nbsp; </Container>&nbsp; &nbsp; </Router>);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答