React-router在有效路由上不匹配

时间:2016-10-20 11:07:04

标签: javascript reactjs react-router

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

Express服务器返回index.html用于任何URL匹配(我没有在任何URL上收到GET错误,因此我认为这很好)

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

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

示例1)

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

OR

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

http://localhost:3100/test =成功&gt;返回主组件 http://localhost:3100/test/login =失败&gt;给我空白屏幕

示例2)

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

http://localhost:3100/login =成功&gt;返回登录组件

示例3)

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

OR

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

http://localhost:3100/test/login =失败&gt;给我空白屏幕

我使用的是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"

3 个答案:

答案 0 :(得分:0)

尝试使用path="login"代替path="/login"。在嵌套路由中不需要路径前的斜杠。

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

答案 1 :(得分:0)

From express documentation, app.get('/*' uses regular expression. so, '/*' work for 0 to n '/'. Try:

app.get('/.*

/.* should resolve '/' + 0 to n caractères.

Regards

答案 2 :(得分:0)

I think the problem lies more with the way you are rendering your app than react-router itself, since you are not getting a route not found message but a blank screen, I suggest the following.

when you create your history object do the following

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');

Your route configuration will then look like this

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

Your App component would then look something like this

export const App extends Component = {
 render() {
   return(
    <div class='app-container'>
     {this.props.children}
    </div>
   )
 }
}

App.propTypes = {
 children: PropTypes.element.isRequired
}

export default App;

You'll then be able to access and render the component Login @ /test/login