React 4.0.0 BrowserRouter渲染所有路径

时间:2017-08-13 20:53:45

标签: reactjs meteor react-router

我正在尝试使用react和meteor进行用户注册的简单发短信应用,当我尝试添加路由时:

**//main.js**
import React from "react";
import ReactDOM from "react-dom";
import {Meteor} from "meteor/meteor";
import {Tracker} from "meteor/tracker";
import { BrowserRouter, Route, browserHistory } from 'react-router-dom'

import {Texts} from "./../imports/api/Text";
import App from "./../imports/ui/App";
import Name from "./../imports/ui/Name";
import NotFound from "./../imports/ui/NotFound"

Meteor.startup(() => {
    Tracker.autorun(() => {
        let texts = Texts.find().fetch();
        console.log(texts);
        console.log(browserHistory);
        const routes = (
            <BrowserRouter>
                <div>
                    <Route path="/chat" render={()=>{
                        return <App texts={texts} />
                    }}/>
                    <Route path="*" component={NotFound}/>
                </div>
            </BrowserRouter>
        );
        ReactDOM.render(routes, document.getElementById("app"));
    });
});


**//NotFound.js**
import React from "react";

export default class NotFound extends React.Component{
    render(){
        return <p>URL not found</p>
    }
}

它将两个内容呈现在屏幕上,我看到我的错误404文本和我的短信应用程序。我的问题是,当我没有识别出Route(例如“/ asddkib”)时,如何让NotFound页面呈现,并且当我走到正确的路径(“/ chat”)时让它消失(只是应用程序) ?现在,如果我去/聊天,那么两者都会被渲染到屏幕上。

2 个答案:

答案 0 :(得分:1)

使用switch语句

 import { BrowserRouter, Route, Switch, browserHistory } from 'react-router-dom', 
 <BrowserRouter>
            <Switch>
                <App path="/chat" texts={texts}/>
                <Route  component={NotFound}/>
            </Switch>
  </BrowserRouter>

答案 1 :(得分:1)

您正在寻找路由器的反应功能。

将您的导入从“react-router”更改为:

import { BrowserRouter, Route, Switch, browserHistory } from 'react-router-dom',

然后,将Switch组件添加到渲染中:

<BrowserRouter>
        <Switch>
            <Route path="/chat" render={()=>{
                return <App texts={texts} />
            }}/>
            <Route  component={NotFound}/>
        </Switch>
</BrowserRouter>