如果我通过主页运行我的网站,则它会很好运行,因为启动状态设置为false,因此按钮可以正确呈现。我的问题是,当我直接进入/ login页面时,我想将状态设置为true。谁能给我个主意?
import React from 'react'
import { NavLink } from 'react-router-dom'
import '../styles/NavBar.css'
import logo from '../res/pwrlogo.png'
class NavBar extends React.Component {
constructor(props) {
super(props);
this.loginPageOn = this.loginPageOn.bind(this);
this.loginPageOff = this.loginPageOff.bind(this);
this.state = { isloginPageOn: false }
}
loginPageOn() {
this.setState({ isloginPageOn: true })
console.log(this.state)
}
loginPageOff() {
this.setState({ isloginPageOn: false })
console.log(this.state)
}
render() {
const isloginPageOn = this.state.isloginPageOn;
let navlink;
if (isloginPageOn) {
navlink = <NavLink to='/' className="rightButton" onClick={this.loginPageOff}>Strona główna</NavLink>
}
else {
navlink = <NavLink to='/login' className="rightButton" onClick={this.loginPageOn}>Logowanie</NavLink>
}
return (
<div className="topnav">
<img src={logo} alt="Logo" />
{navlink}
</div>)
}
答案 0 :(得分:0)
您可以使用location
对象,并使用componentWillReceiveProps
在组件加载时获取当前路径名(取决于您的React版本)。因此,您将得到以下内容:
componentWillReceiveProps(nextProps) {
if (this.props.location.pathname !== nextProps.location.pathname) {
if (nextProps.location.pathname === '/login') {
this.setState({ isloginPageOn: true });
} else {
this.setState({ isloginPageOn: false });
}
}
}
这样,您将不需要功能loginPageOn
和loginPageOff
,因为状态将从componentWillReceiveProps
更新。
有多种访问location
对象的方法,具体取决于您的react-router版本。您可以了解有关here的更多信息。