首页 文章

在反应路由器dom中使用渲染与私有路由

提问于
浏览
0

我试图使用react router dom v4在私有路由中呈现两个组件 . 这可以使用普通路由,但在使用自定义路由时似乎不是这种情况 . 我收到以下错误:“警告:React.createElement:类型无效 - 期望一个字符串(对于内置组件)或类/函数(对于复合组件)但得到:undefined . 您可能忘记导出组件从它定义的文件中,或者你可能混淆了默认和命名的导入 . “
自定义路线(已验证)

return (
      <Route
        {...rest}
        render={props =>
          this.currentUser()
            ? <Component currentUser={this.currentUser} {...props} />
            : <Redirect
                to={{
                  pathname: '/auth/login',
                  state: { from: props.location }
                }}
              />
        }
      />
    )

然后在我的路线中我想要这样的东西

return (
      <div>
        <Switch location={isModal ? this.prevLocation : location}>
          <Authenticated path="/" exact component={Main} />
          <Route path="/auth/register" exact component={Register} />
          <Route path="/auth/login" exact component={Login} />
          <Authenticated
            path="/clients/:id/edit"
            render={(props) => ( // Not working as expected. Works fine using Route instead of Authenticated
              <div>
                <Main />   
                <ClientEdit />
              </div>
            )}
          />
        </Switch>
        {isModal ?
          <Authenticated
            path='/clients/new'
            component={ClientNew}
          />
        : null}
        {isModal ?
          <Authenticated
            path='/clients/:id/edit'
            component={ClientEdit}
          />
        : null}
      </div>
    );

2 回答

  • 1

    在您的protectedRoute组件中,您没有收到或使用您在行中发送的 render 道具:

    render={(props) => ( 
      <div>
        <Main />   
        <ClientEdit />
      </div>
    )}
    

    而不是使用渲染发送 component prop中的组件,如:

    component={(props) => ( 
      <div>
        <Main />   
        <ClientEdit />
      </div>
    )}
    

    还要检查路由器的文件,看看何时使用 component prop以及何时使用 render prop . 如果您可以更改 protectedRoute 来处理两者,那会好得多 .

  • 0

    我认为您需要创建一个返回的自定义组件:

    return(
      <div>
       <Main />   
       <ClientEdit />
      </div>)
    

    然后导入它并在经过身份验证的组件中使用它,如下所示:

    <Authenticated
       path="/clients/:id/edit"
       component={CustomComponent}
     />
    

    编辑:如果提供,您还可以在Authenticated组件中处理渲染道具:

    if (this.props.render && this.currentUser()) {
      return(
        <Route
          {...rest}
          render={this.props.render}
        />
    } else {
        return (
           <Route
             {...rest}
             render={props => this.currentUser() ?
                <Component currentUser={this.currentUser} {...props} /> : 
                <Redirect
                    to={{
                      pathname: '/auth/login',
                      state: { from: props.location }
                    }}
                 />
              }
            />
          )
    }
    

相关问题