0

我是React新手,看着這個ReactTraining。我想使我的一些路徑是私人的(這樣你只能在登錄時查看它們)。我能夠驗證用戶是否正常,並將他們指向新頁面,但現在我想「保護」該頁面,以便在登錄後才能訪問該頁面。我發現幾個不同的sources似乎使用相同的「PrivateRoute 「功能如下。一切似乎都工作很好,到目前爲止(和有意義),除了這下面的代碼「......休息」的一部分:React JS錯誤「... rest」語法錯誤:意外的代幣

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
     <Component {...props}/> 
    ) : (
     <Redirect to={{ 
     pathname: '/login', 
     state: { from: props.location } 
     }}/> 
    ) 
)}/> 
) 

我收到以下錯誤:

Uncaught Error: Cannot find module "./components/Login" 
    at webpackMissingModule (router.js:9) 
    at Object.<anonymous> (router.js:9) 
    at __webpack_require__ (bootstrap 18b9132…:555) 
    at fn (bootstrap 18b9132…:86) 
    at Object.<anonymous> (index.js:22) 
    at __webpack_require__ (bootstrap 18b9132…:555) 
    at fn (bootstrap 18b9132…:86) 
    at Object.<anonymous> (bootstrap 18b9132…:578) 
    at __webpack_require__ (bootstrap 18b9132…:555) 
    at bootstrap 18b9132…:578 
webpackMissingModule @ router.js:9 
(anonymous) @ router.js:9 
__webpack_require__ @ bootstrap 18b9132…:555 
fn @ bootstrap 18b9132…:86 
(anonymous) @ index.js:22 
__webpack_require__ @ bootstrap 18b9132…:555 
fn @ bootstrap 18b9132…:86 
(anonymous) @ bootstrap 18b9132…:578 
__webpack_require__ @ bootstrap 18b9132…:555 
(anonymous) @ bootstrap 18b9132…:578 
(anonymous) @ bootstrap 18b9132…:578 
webpackHotDevClient.js:233 Error in ./src/components/Login.js 
Syntax error: Unexpected token (16:46) 

    14 | 
    15 | 
> 16 | const PrivateRoute = ({ component: Component, ...rest }) => (
    |            ^
    17 | <Route {...rest} render={props => (
    18 | fakeAuth.isAuthenticated ? (
    19 |  <Component {...props}/> 

@ ./src/router.js 25:13-42 

它似乎我正在導入我應該做的所有事情,所以我的想法是,我沒有安裝應該安裝的東西。

有誰知道我可能需要安裝以解決此錯誤?

回答

3

spread ... syntax不是es2015react babel預設的一部分。這是目前的第三階段提案。要啓用傳播支持你的項目做出反應,安裝通天階段3插件:

npm install --save-dev babel-preset-stage-3 

,並把它添加到您的.babelrc

{ 
    "presets": [ 
    "es2015", 
    "react", 
    "stage-3" 
    ] 
} 
+0

感謝您的幫助!工作很棒! – Rbar