【问题标题】:How to render a component without using a Route element如何在不使用 Route 元素的情况下渲染组件
【发布时间】:2021-03-16 18:32:50
【问题描述】:

这是我的 React 组件:

const Auth = () => {  

useEffect(() => { 
document.body.classList.add("bg-default");  
return () => {  
document.body.classList.remove("bg-default");      
}    
}, [])    

const { isAuthenticated } = useAuth0();  

if (isAuthenticated){  
return <AdminLayout><Dashboard/></AdminLayout>      
}  return ( 

但这是一个我无法理解的问题。 AdminLayout 适用于每个组件,但是当我以上述方式返回它时,我得到:TypeError: Cannot read property 'pathname' of undefined

错误在于:

<AdminNavbar {...this.props} 
brandText{this.getBrandText(this.props.location.pathname)} />

我认为这是关于 react-router 但我不知道如何修复它,我对 react-router 不是很有信心。

我是这样固定的:

const Auth = () => {  

useEffect(() => { 
document.body.classList.add("bg-default");  
return () => {  
document.body.classList.remove("bg-default");      
}    
}, [])    

const { isAuthenticated } = useAuth0();  

if (isAuthenticated){  
return <AdminLayout><Dashboard/></AdminLayout>      
}  return ( 

但这是一个我无法理解的问题。 AdminLayout 适用于每个组件,但是当我以上述方式返回它时,我得到:TypeError: Cannot read property 'pathname' of undefined

错误在于:

<AdminNavbar {...this.props} 
brandText{this.getBrandText(this.props.location.pathname)} />

【问题讨论】:

  • 第一个问题:不能在基于类的组件中使用钩子。第二个问题:在根级别,一个类组件只能包含标题中列出的东西。在基于类的组件中,render 方法等价于函数组件的主体(这是一个巨大的过度简化)。但是,假设我们可以在基于类的组件中使用钩子,那么解决方法就是简单地将代码移动到渲染方法中。

标签: javascript reactjs react-router


【解决方案1】:

看起来AdminLayout 需要一个名为 location 的道具,它本身有一个名为 pathname 的道具。我想您可以将其呈现为&lt;AdminLayout location={window.location} /&gt;,或者将this.props.location.pathname 更改为window.location.pathname,这假设您尝试根据用户所在的位置呈现不同的文本。

【讨论】:

    猜你喜欢
    • 2023-02-22
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多