我想根据用户是否登录来呈现组件
<PrivateRoute
authed={isAuthenticated} path="/unapproved-list/"
component={UnapprovedList}
/>
PrivateRoute组件是这样设置的
import React, { Component } from 'react';
import { Redirect } from 'react-router';
import { Route } from 'react-router-dom';
const PrivateRoute = ({component, authed, ...rest}) => {
console.log("in private route, authed: " + authed);
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
export default PrivateRoute;
然而,当身份验证为真时,这行
Component {...props} />
导致以下错误
TypeError: instance.render is not a function
finishClassComponent
node_modules/react-dom/cjs/react-dom.development.js:17160
17157 | } else {
17158 | {
17159 | setIsRendering(true);
> 17160 | nextChildren = instance.render();
| ^
17161 |
17162 | if ( workInProgress.mode & StrictMode) {
17163 | instance.render();
不确定如何构建我的私有路由以正确呈现组件。我宁愿不改变组件结构,目前它就像下面的
const UnapprovedList = () => {
const [unapprovedCoops, setUnapprovedCoops] = React.useState([]); ...
return (
<>
{loadErrors && (
<strong className="form__error-message">
{JSON.stringify(loadErrors)}
</strong>
)}
{loadingCoopData && <strong>Loading unapproved coops...</strong>}
<RenderCoopList link={"/approve-coop/"} searchResults={unapprovedCoops} columnOneText={"Unapproved Entities"} columnTwoText={"Review"} />
</>
)
}
export default UnapprovedList;
<Component {...props} />
行指的是从React导入的Component
类,而不是component
道具,因为第一个字母是大写还是小写。
尝试以下操作:
const PrivateRoute = ({ component: WrappedComponent, authed, ...rest }) => {
console.log("in private route, authed: " + authed);
return (
<Route
{...rest}
render={(props) => authed === true
? <WrappedComponent {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}