如何使用 React HashRouter 和 Apollo 客户端渲染反应类组件?
Posted
技术标签:
【中文标题】如何使用 React HashRouter 和 Apollo 客户端渲染反应类组件?【英文标题】:How to render react class component with React HashRouter and Apollo client? 【发布时间】:2021-12-12 22:59:30 【问题描述】:我在一个项目中工作,我必须只使用 React 类组件,并且我正在从 Apollo 服务器获取数据。 问题是在 Chrome 中只呈现 Navbar.jsx。当我在其中一个链接上导航时,屏幕上没有任何内容。控制台中也没有任何错误。 有人可以帮我吗? 谢谢! 这是 Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import
ApolloClient,
InMemoryCache,
ApolloProvider,
from "@apollo/client";
import HashRouter from 'react-router-dom';
export const client = new ApolloClient(
uri: ' http://localhost:4000/',
cache: new InMemoryCache()
);
ReactDOM.render(
<React.StrictMode>
<HashRouter >
<ApolloProvider client=client>
<App />
</ApolloProvider>
</HashRouter>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
这里是 App.js:
import React, Component from 'react'
import './App.css';
import Switch, Route from 'react-router-dom'
import Navbar from './Components/Navbar';
import Bikes from './Pages/Bikes';
import Books from './Pages/Books';
import client from './index';
import GET_QUERY from './GraphQl/Queries'
class App extends Component
state=
currencies: [],
componentDidMount = async ()=>
const response = await client.query(
query:GET_QUERY
)
this.setState(
currencies:response.data.currencies
)
render()
return (
<div className="App">
<Navbar currencies=this.state.currencies/>
<Switch>
<Route exact path="/bikes" component=Bikes />
<Route exact path="/books" component=Books />;
</Switch>
</div>
);
export default App;
这里是 Navbar.jsx:
import React, Component from 'react'
import Link from 'react-router-dom'
import styled from 'styled-components'
import withRouter from 'react-router';
const StyledLink = styled(Link)`
`;
class Navbar extends Component
render()
return (
<nav>
<div>
<ul>
<li>
<StyledLink to="/bikes" replace>Bikes</StyledLink>
</li>
<li>
<StyledLink to="/books" replace>Books</StyledLink>
</li>
</ul>
</div>
</nav>
)
export default withRouter(Navbar)
其中一页 Bikes.jsx:
import React, Component from 'react'
import client from '../index'
import GET_QUERY from '../GraphQl/Queries'
import CATEGORY_VAR from '../GraphQl/Variables'
class Bikes extends Component
state=
bikesArt: []
componentDidMount = async ()=>
const response = await client.query(
query: GET_QUERY,
variables: CATEGORY_VAR
)
this.setState(
bikesArt:response.data.category.products
)
render()
return (
<div>
<h1>Bikes</h1>
</div>
)
export default Bikes
【问题讨论】:
【参考方案1】:解决了。这是CSS。导航栏覆盖了页面中唯一的 <h2>
标签
【讨论】:
以上是关于如何使用 React HashRouter 和 Apollo 客户端渲染反应类组件?的主要内容,如果未能解决你的问题,请参考以下文章
React 中的 HashRouter 和 BrowserRouter 有啥区别?
react-router-dom中的BrowserRouter和HashRouter
react-router-dom中的BrowserRouter和HashRouter
react-router-dom中的BrowserRouter和HashRouter