我的代码正在编译并运行,但只是不起作用。我不知道我做错了什么。以下代码示例(我相信是相关的)摘录自各自的文件。
的package.json
"dependencies": {
"@types/react": "^15.0.28",
"@types/react-dom": "^15.5.0",
"@types/react-router": "^4.0.11",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.1.1",
"typescript": "^2.3.4"
},
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import Bids from './Bids';
import { MemoryRouter, Route, Switch} from 'react-router';
ReactDOM.render(
<MemoryRouter>
<Switch>
<Route exact path="/bids" component={() => <Bids />} />
<Route exact path="/" component={() => <App />} />
</Switch>
</MemoryRouter>
,
document.getElementById('root') as HTMLElement
);
Bids和App都是具有简单“hello world”渲染功能的反应组件
class App extends React.Component<{}, null> {
render() {
我遇到的问题是我无法让我的程序呈现非默认路径。
如果我导航到“http://localhost:3000/”,我会收到App组件 如果我导航到“http://localhost:3000/bids”,我会收到应用程序组件 如果我导航到“http://localhost:3000/randomString”,我会收到App组件。
如果我在代码中切换它们(即“/ bid”指向App并且“/”指向Bids),那么我只能在任何路径上看到Bids组件。
有什么想法吗?
答案 0 :(得分:0)
感谢评论(杰西和亚历克斯),答案就出现了。切换到react-router-dom和BrowserRouter解决了这个问题。
"@types/react": "^15.0.28",
"@types/react-dom": "^15.5.0",
"@types/react-router-dom": "^4.0.4",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.1.1",
"typescript": "^2.3.4"
和
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import Bids from './Bids';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/bids" component={() => <Bids />} />
<Route exact path="/" component={() => <App />} />
</Switch>
</BrowserRouter>
,
document.getElementById('root') as HTMLElement
);
答案 1 :(得分:0)
您最多会安装软件包react-router-dom
yarn add react-router-dom -W
npm i react-router-dom --save