问一个关于react-router的问题

这样配置好以后,每次调用Route都会报错
“You tried to redirect to the same route you're currently on: "/home"”
请问该怎么优化呢?

      <Router>
        <div>
          <Nav/>
          <Redirect to="/home"></Redirect>
          <Route path="/comment" component={CommentBox}></Route>
          <Route path="/home" component={Home}></Route>
          <Route path="/productList" component={ProductList}></Route>
          <Route path="/showdetail" component={ShowDetail}></Route>
          <Route path="/showdetail/:id" component={ShowDetail}></Route>
          <Route path="/login" component={Login}></Route>
          <Route path="/private" component={Private}></Route>
        </div>
      </Router>
阅读 8.2k
6 个回答

你可以在把你的<Route> 外面包一层<Switch>

同时把你的 Redirect 放到最后面

<Router>
        <div>
          <Nav/>
          <Route path="/" render={() => (<Redirect to="/home"/>)}></Route >
          <Route path="/comment" component={CommentBox}></Route>
          <Route path="/home" component={Home}></Route>
          <Route path="/productList" component={ProductList}></Route>
          <Route path="/showdetail" component={ShowDetail}></Route>
          <Route path="/showdetail/:id" component={ShowDetail}></Route>
          <Route path="/login" component={Login}></Route>
          <Route path="/private" component={Private}></Route>
        </div>
      </Router>

把你的<Redirect to="/home"></Redirect>放最后应该也可以。

新手上路,请多包涵

给path="/"前面加一个exact

Redirect用的位置有问题。应该是在满足某个条件的情况下,才使用Redirect执行路由重定向操作。但你现在的写法是,不管访问任何URL,Redirect这个组件都会被渲染,执行重定向动作,可能会和下面的Route匹配当前URL的操作冲突,因为理论上,当Route匹配URL时,当前的URL已经被Redirect重新修改过。具体现象待验证,但Redirect的用法是有问题的。

就用exact就可以啦
clipboard.png
跟什么前后位置没有关系

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题