React路由器在有效路由上不匹配



无论我做什么,我都无法让这个react路由器在路径的第二部分匹配。

Express服务器正在为任何URL匹配返回index.html(我在任何URL上都没有得到GET错误,所以我认为这很好(

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

以下是我尝试过的一些路由示例,根据react router docs ,这些路由应该是有效的规则

示例1(

<Route path="test">
  <IndexRoute component={Home} />
  <Route path="/login" component={Login} />
</Route>

<Route path="test">
    <IndexRoute component={Home} />
    <Route path="/login" component={Login} />
</Route>

http://localhost:3100/test=成功>返回主页组件http://localhost:3100/test/login=失败>给我一个空白屏幕

示例2(

 <Route path="/login" component={Login} />

http://localhost:3100/login=成功>返回登录组件

示例3(

 <Route path="/test/login" component={Login} />

 <Route path="test/login" component={Login} />

http://localhost:3100/test/login=失败>给我一个空白屏幕

我使用的是2.5版本,如有任何帮助,不胜感激!

**反作用路由器的纱线转储**

react-router@^2.5.0:
  version "2.8.1"
  resolved "https://registry.yarnpkg.com/react-router/-/react-router-2.8.1.tgz#73e9491f6ceb316d0f779829081863e378ee4ed7"
  dependencies:
    history "^2.1.2"
    hoist-non-react-statics "^1.2.0"
    invariant "^2.2.1"
    loose-envify "^1.2.0"
    warning "^3.0.0"

尝试path="login"而不是path="/login"。嵌套管线中不需要在路径前加斜线。

<Route path="test/">
  <IndexRoute component={Home} />
  <Route path="login" component={Login} />
</Route>

在express文档中,app.get('/*'使用正则表达式。因此,'/*'工作于0到n'/'。尝试:

app.get('/.*

/.*应解析'/'+0到n个caractères。

问候

我认为问题更多地在于你呈现应用程序的方式,而不是反应路由器本身,因为你得到的不是未找到路由的消息,而是一个空白屏幕,我建议如下。

创建历史对象时,执行以下

import { useRouterHistory } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
// ========================================================
// Browser History Setup
// ========================================================
const createHistory = (basename) => {
  return useRouterHistory(createBrowserHistory)({
    basename: basename
  })
}
const history = createHistory('/test');

然后,您的路线配置将看起来像这个

<Route path="/" component={App} >
  <IndexRoute component={Home} />
  <Route path="login" component={Login} />
</Route>

然后你的应用程序组件会看起来像这个

export const App extends Component = {
 render() {
   return(
    <div class='app-container'>
     {this.props.children}
    </div>
   )
 }
}
App.propTypes = {
 children: PropTypes.element.isRequired
}
export default App;

然后,您将能够访问并呈现组件Login@/test/login

最新更新