React路由器V-5.2.0在离开主页导航时不工作



索引.tsx

import {Router, } from 'react-router';
import { createHashHistory } from 'history';
const hashHistory = createHashHistory();
hashHistory.push("/");
ReactDOM.render(
<Provider {...stores}>
<Router history={hashHistory} >
<App />
</Router>
</Provider>,
document.getElementById('root') as HTMLElement
);

应用程序.tsx

import Router from './components/Router';
public render() {
return <Router/>;
}

路由器

import { Route, Switch } from 'react-router';
const Router = () => {
const UserLayout = utils.getRoute('/user').component;
const AppLayout = utils.getRoute('/').component;

return (
<Switch>
<Route path="/user" render={(props: any) => <UserLayout {...props} />} />
<Route path="/test" render={() => <div>Test</div>} />
<ProtectedRoute path="/" render={(props: any) => <AppLayout {...props} exact />} />
</Switch>
);
};

电子

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const isDev = require('electron-is-dev');
const path = require('path');
const url = require('url');
var history = require('connect-history-api-fallback');
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
nodeIntegration: true,
webPreferences: {
webSecurity: false
}
});
mainWindow.loadURL(!isDev ? 'http://localhost:3000' : url.format({
pathname: path.join(__dirname,'../build/index.html'),
protocol: 'file:',
slashes: true,
}));

mainWindow.webContents.openDevTools();
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
app.on('ready', () => console.log('Ready', history({index: 'index.html'})));
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit();
}
});
console.log('global window', __dirname);
app.on('activate', function () {
console.log('mainWindow', __dirname);
if (mainWindow === null) {
console.log('mainWindowNull', __dirname);
createWindow();
}
});

我也试过使用"react router dom",但它也不起作用。这种情况只发生在生产中。即使我重新加载主页,主页也会加载。但当我离开主页时,例如,当我点击登录按钮时,它会抛出一个错误,屏幕是白色的。在我的网络选项卡中,它显示file:///D:红色。而且我没有使用Webpack。

以及使其与react-router-dom一起工作的示例。

在您的index.tsx文件中,像一样导入

import { BrowserRouter } from 'react-router-dom';
<BrowserRouter>
<App />
</BrowserRouter>

redux存储也将包装浏览器路由器,因为你正在使用它。不需要导入历史记录和/或创建hashHistory。

你可以这样申报你的路线:

<Switch>
<Route exact path="/home" component={Home} />
</Switch>

<Route
path="/blog/:slug"
render={({ match }) => {
// Do whatever you want with the match...
return <div />;
}}
/>

现在,如果您想导航到组件内部的任何位置,您需要导入withRouter

import { withRouter } from 'react-router-dom';

组件内部

并用它包裹出口,就像:

export default withRouter(DemoComponent);

这将把历史对象作为道具传递给您的组件。要导航离开,只需拨打:

props.history.push('/'); // can be anything here you want to navigate to

如果你不使用功能组件,它可能看起来像这样:

this.props.history.push('/');

最新更新