在Reaction中,如何呈现作为道具传入的无状态组件? [英] In React, how do I render a stateless component that is passed in as a prop?
本文介绍了在Reaction中,如何呈现作为道具传入的无状态组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要根据用户是否登录来呈现组件
<PrivateRoute
authed={isAuthenticated} path="/unapproved-list/"
component={UnapprovedList}
/>
PrivateRouting组件的设置如下
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;
但是,当身份验证为True时,此行
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} />
行引用从Reaction导入的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}}} />}
/>
)
}
这篇关于在Reaction中,如何呈现作为道具传入的无状态组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文