【发布时间】:2020-03-22 17:30:01
【问题描述】:
使用 React,我试图在渲染特定页面时部分显示页脚。对于所有其他页面,应显示整个页脚。
这是我的代码,但它仅在刷新我不需要的页面时才有效。我应该如何编码以使其按预期工作?
window.location.href 是否适合这种情况? 使用 componentWillMount 是否也适合这种情况?
非常感谢! 卡洛斯
class Footer extends Component {
constructor() {
super()
this.state = {
currentUrl: '',
}
}
UNSAFE_componentWillMount() {
this.setState({ currentUrl: window.location.href })
}
componentWillUnmount() {
this.setState({ currentUrl: '' })
}
render() {
const { currentUrl } = this.state
return (
<footer className="section-grid">
{currentUrl !==
`${url || url_beta}/jetzt-vorsorgen/vorsorge-planen` ? (
<RB.Container>
<RB.Row>
<RB.Col
md={{ span: 11, offset: 1 }}
lg={{ span: 6, offset: 0 }}
>
<RB.Row>
<RB.Col md={6} lg={{ span: 12, offset: 0 }}>
<p className="headline">Kunde werden</p>
<Button
elementType="Link"
pathLink="/jetzt-vorsorgen"
size="lg"
block
variant="light btn-footer"
>
<i className="fa fa-file-text-o" />{' '}
Angebot einholen
</Button>
<Button
className="demo demo-right"
elementType="Link"
pathLink="/demokonto"
size="lg"
variant="primary btn-footer"
>
Zum Demokonto{' '}
</Button>
</RB.Col>
<RB.Col
md={6}
lg={{ span: 10, offset: 0 }}
xl={{ span: 6, offset: 0 }}
>
<p className="headline">
Newsletter anmelden
</p>
<NewsletterForm />
</RB.Col>
</RB.Row>
</RB.Col>
<RB.Col
md={{ span: 11, offset: 1 }}
lg={{ span: 6, offset: 0 }}
>
<FooterMenuList />
</RB.Col>
</RB.Row>
</RB.Container>
) : null}
<RB.Container className="cp">
<RB.Row>
<RB.Col
lg={{ span: 6, offset: 6 }}
md={{ span: 11, offset: 1 }}
xs={12}
>
<RB.Row as="ul">
<RB.Col as="li" sm={4}>
<Link to="/datenschutz">
Datenschutzerklärung
</Link>
</RB.Col>
<RB.Col as="li" sm={4}>
<Link to="/impressum">Impressum</Link>
</RB.Col>
<RB.Col as="li" sm={4}>
<p>
{new Date().getFullYear()}
</p>
</RB.Col>
</RB.Row>
</RB.Col>
</RB.Row>
</RB.Container>
</footer>
)
}
}
export default Footer
【问题讨论】:
-
你有处理路由的东西吗?比如 react-router?为什么将 window.location.href 存储在一个状态中?这没有任何作用,因为状态永远不会更新,并且 window.location.href 如果发生变化也不会触发重新渲染。
-
嗨 Nicolas,是的,我们在网络上使用 react-router。你的意思是这将是如何实现的?抱歉,我是编码新手,对于您关于为什么 location.href 处于状态的问题,我没有答案。我只是用我发现的搜索结果尝试了它(不完全)对我有用的方式..
-
我不知道您使用的是哪个版本,但您可能想查看这个问题。答案指出了如何使用反应路由器读取网址:stackoverflow.com/questions/42253277/…
标签: javascript reactjs router conditional-operator