鍍金池/ 問答/HTML/ 問一個(gè)關(guān)于react-router的問題

問一個(gè)關(guān)于react-router的問題

這樣配置好以后,每次調(diào)用Route都會(huì)報(bào)錯(cuò)
“You tried to redirect to the same route you're currently on: "/home"”
請(qǐng)問該怎么優(yōu)化呢?

      <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>
回答
編輯回答
怪痞

Redirect用的位置有問題。應(yīng)該是在滿足某個(gè)條件的情況下,才使用Redirect執(zhí)行路由重定向操作。但你現(xiàn)在的寫法是,不管訪問任何URL,Redirect這個(gè)組件都會(huì)被渲染,執(zhí)行重定向動(dòng)作,可能會(huì)和下面的Route匹配當(dāng)前URL的操作沖突,因?yàn)槔碚撋?,?dāng)Route匹配URL時(shí),當(dāng)前的URL已經(jīng)被Redirect重新修改過。具體現(xiàn)象待驗(yàn)證,但Redirect的用法是有問題的。

2017年4月1日 23:49
編輯回答
嘟尛嘴

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

同時(shí)把你的 Redirect 放到最后面

2017年6月22日 23:57
編輯回答
脾氣硬

就用exact就可以啦
clipboard.png
跟什么前后位置沒有關(guān)系

2017年1月23日 00:32
編輯回答
懷中人

把你的<Redirect to="/home"></Redirect>放最后應(yīng)該也可以。

2017年12月20日 18:14
編輯回答
半心人

給path="/"前面加一個(gè)exact

2017年6月8日 23:54
編輯回答
小曖昧
<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>
2017年10月23日 00:46