iT邦幫忙

0

react-router 驗證問題(來自官方範例微調)

代碼(141行開始)裡有備註我所遇到的問題,想請問為什麼會這樣?
如果一定要觸發這個 useEffect 的話,該如何調整比較好?

以下為代碼原141行描述

// 請問這裡為什麼在登入後就不會保證執行了?
// 在 /protected, /protected2 之間交互訪問,可以看到該 console 並不會觸發
// 但是從 /public 訪問到 /protected1 或 /protected2 就會觸發
// 我對 Route 的認知是,當路由 match 成功後將會渲染頁面,這樣不是應該在執行這個 useEffect 嗎?

這是官方的 Redirects (Auth) EXAMPLE

/images/emoticon/emoticon41.gif 謝謝您的幫助

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

3
listennn08
iT邦高手 5 級 ‧ 2021-07-15 09:55:22
最佳解答

你在登入之前進到 PrivateRoute 都會 redirect 到 login 這個 component
登入之後切換 protected 跟 pretected2 都是在 AuthComponent 底下,所以不會重複觸發 useEffect,加上 location 就行了

useEffect(() => {
  console.log(location);
}, [location]);

為什麼不會重複觸發的原因可以看一下 useEffect 的 API 文件
簡單來說如果第二個參數是空陣列的話,就只會在 componentDidMount 的時候觸發

frank575 iT邦新手 4 級 ‧ 2021-07-15 11:52:39 檢舉

謝謝你的解答,你的方式也是我目前的解法

重複觸發原因我明白,但是在 AuthComponent 底下不會重複觸發是為什麼呢?

這兩個場景難道不是相同的嗎?

場景一

<!-- 
AuthComponent 在各自獨立的 PrivateRoute 的 Route render 內,這樣的 AuthComponent 不該是各自獨立的嗎?

像以下偽代碼(場景二)一樣
-->
<Route
  {...rest}
  render={({ location }) => (
    <AuthComponent location={location}>{children}</AuthComponent>
  )}
/>

<PrivateRoute path="/protected">
  <ProtectedPage />
</PrivateRoute>
<PrivateRoute path="/protected2">
  <ProtectedPage2 />
</PrivateRoute>

場景二

function Component() {
    useEffect(() => {
        // 這裡就會各自觸發
    }, [])
    return null
}

<div>
    <Component />
    <Component />
</div>

如果是在 AuthComponent 底下切換的話,代碼不是應該是像這樣嗎?

<AuthComponent>
    <Route path='/protected' />
    <Route path='/protected2' />
</AuthComponent>

我看了一下發現你說的沒有錯,然後我看到你在 PrivateRoute 使用了 Route render 去判斷現在的頁面

<Route
  {...rest}
  render={({ location }) => (
    <AuthComponent location={location}>{children}</AuthComponent>
  )}
/>

就去看了一下這個文件,文件有寫到

This allows for convenient inline rendering and wrapping without the undesired remounting explained above.

所以看起來是這個原因

frank575 iT邦新手 4 級 ‧ 2021-07-15 13:14:16 檢舉

明白了!!!

看來是文檔看的不夠透徹,這下可是恍然大悟了,謝謝你的幫助,這問題卡了我不少的時間QQ

/images/emoticon/emoticon41.gif

我要發表回答

立即登入回答