gpt4 book ai didi

javascript - React Router 只识别索引路由

转载 作者:行者123 更新时间:2023-12-02 06:55:22 25 4
gpt4 key购买 nike

我有 2 条路线,//about我已经测试了几个。所有路由只渲染 home 组件,即 / .

当我尝试一条不存在的路线时,它会识别出很好并显示警告 Warning: No route matches path "/example". Make sure you have <Route path="/example"> somewhere in your routes

App.js

import React from 'react';
import Router from 'react-router';
import { DefaultRoute, Link, Route, RouteHandler } from 'react-router';
import {Home, About} from './components/Main';

let routes = (
<Route name="home" path="/" handler={Home} >
<Route name="about" handler={About} />
</Route>
);

Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});

./components/Main

import React from 'react';

var Home = React.createClass({
render() {
return <div> this is the main component </div>
}
});

var About = React.createClass({
render(){
return <div>This is the about</div>
}
});

export default {
Home,About
};

我试过添加一个明确的路径到 about 无济于事。 <Route name="about" path="/about" handler={About} />

我偶然发现了这个 stackoverflow Q但在它的答案中找不到救赎。

任何人都可以阐明可能是什么问题吗?

最佳答案

使用 ES6 和最新的 react-router 看起来像这样:

import React from 'react';
import {
Router,
Route,
IndexRoute,
}
from 'react-router';

const routes = (
<Router>
<Route component={Home} path="/">
<IndexRoute component={About}/>
</Route>
</Router>
);

const Home = React.createClass({
render() {
return (
<div> this is the main component
{this.props.children}
</div>
);
}
});

//Remember to have your about component either imported or
//defined somewhere

React.render(routes, document.body);

附带说明,如果您想将未找到的路由与特定 View 匹配,请使用:

<Route component={NotFound} path="*"></Route>

注意路径设置为*

同时编写您自己的 NotFound 组件。

我的看起来像这样:

const NotFound = React.createClass({
render(){
let _location = window.location.href;
return(
<div className="notfound-card">
<div className="content">
<a className="header">404 Invalid URL</a >
</div>
<hr></hr>
<div className="description">
<p>
You have reached:
</p>
<p className="location">
{_location}
</p>
</div>
</div>
);
}
});

关于javascript - React Router 只识别索引路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32421598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com