如果未登录React Token auth

时间:2019-05-29 09:37:22

标签: reactjs react-router

我有这个应用程序,前端是React,后端是Laravel。我使用Laravel Passport进行了身份验证系统。用户登录后,我将令牌保存在本地存储中。如果用户未登录,我想自动重定向到/login。基本上,如果用户未登录,该用户将无法执行任何操作。我尝试了此操作:

<BrowserRouter>
    <Route path="/login" exact component={FormularAuth} />
        {
          isAuthenticated ? (
            <React.Fragment>
              *ALL OTHER ROUTES ARE HERE, AND IF LOGGED IN, IT WORKS*
            </React.Fragment>
           ) : ( 
                   window.location = '/login')
               )
         }
</BrowserRouter>

它会将我发送到/login页,但是它一直在刷新,并且我无法登录或执行任何操作。这是什么问题?

1 个答案:

答案 0 :(得分:0)

反应路由器v4支持使用 "gcheck" : { "mappings" : { "properties" : { "binaryType" : { "type" : "long" }, "checkin" : { "type" : "object" }, "isClubMember" : { "type" : "boolean" }, "location" : { "type" : "geo_point", "ignore_malformed" : true }, "mealTimes" : { "type" : "integer" }, "neighbourhood" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } }, "objectID" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } }, "promotion" : { "type" : "object" }, "rating" : { "type" : "long" } } } }

PrivateRoute

像普通路由一样使用它,并在专用路由中检查身份验证。

// create a private route, if user is not logged in redirect to login page
const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
      isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/login' />
  )} />
)