最近測api時剛好斷線,想說這是一個好機會,就順手先加上api斷線時的頁面跳轉,下面講react-router-dom的 exact、strict的觀念
react-router-dom Route exact strict
參考資料
這算是邏輯問題,用什麼參數到就會有什麼效果,就照官網所寫


但今天我有問題,當我的路徑是樹狀階層時,該怎麼運用?
範例
const BasicExample = () => (
  <Router>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
  </Router>
)
const Topics = ({ match }) => (
    <Route path={`${match.url}/:topicId`} component={Topic}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select a topic.</h3>
    )}/>
)
const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
邊有幾點要注意
1.當你是該<Route>裡的最底路徑,應加上`exact`,不太會解釋但是我想說的就是`'/'`,通常階層式的<Route>應該會有"/"
```  <Router>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
   </Router>```
2.當<Route>後面會接另一層<Route>,若要加條件判斷,只能加`strict`(參照上面的`strict`使用範例),
   
   ```<Router>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route strict path="/topics" component={Topics}/>
     </Router>```
     
    `component={Topics}` 又有子階層<Route>
    
    ```
        const Topics = ({ match }) => (
            <Route path={`${match.url}/:topicId`} component={Topic}/>
            <Route exact path={match.url} render={() => (
            <h3>Please select a topic.</h3>
             )}/>
        )
        
    ```
   
   
   為什麼要談這些?因為想要做錯誤頁面就必須規範好<Route>的撰寫格式,就像說今天沒有規範,其實不管,什麼路徑,都可以秀出東西,而因為通常錯誤頁面是沒有指令`path`的,所以才要理解這兩個參數的觀念
   
   
這是我的根目錄, <Route strict path="/board" component={Board} />,後面一大串的樹狀目錄,所以要用strict限定,下面的/404 頁面還蠻有趣的,我一起使用兩個參數,這也是官方提供的功能,意思是我完全指定當path是/404時,才會跳到這路徑,不然照預設的話,/board跟/404是同路徑串的,但我用strict避開了/one 這階層的路徑,所以我可以大膽的指定,/400,/500等錯誤頁面在這層路徑內
<BrowserRouter>
      <Switch>
        <Route strict path="/board" component={Board} />
        <Route strict exact path="/404" component={NotFound} />
      </Switch>
</BrowserRouter>
這邊也算單純,但也是有一個地雷要注意
在HOC component 裡面,的function 是不能直接return 其他Component的 ,只能在render()裡面return 
例如errorfunction寫法是錯的,
class App extends React{
    constructor(){
    }
    errorfunction(){       
        if (this.state.errorCode !== null) {
          return <Redirect to="/404" />;
        }
    }
    render(){
     return(
     )
    }
}
正確的做法是
class App extends React{
    constructor(){
        this.state={
           errorCode:null
        }
    }
    api(){
        axios(url)
           .then()
           .catch((error)=>{
               if(!error,stutus){
                   this.setState({errorCode:404})
               }
           })
    }
    render(){
        if (this.state.errorCode === 404) {
          return <Redirect to="/404" />;
        }
     return(
     )
    }
}
操作上還是要用this.state來做控制
算是簡單但又充滿醍醐味的路徑配置