gpt4 book ai didi

javascript - 在组件加载到页面 Reactjs 之前,我如何更改我的菜单链接

转载 作者:行者123 更新时间:2023-12-03 20:18:43 25 4
gpt4 key购买 nike

我试图在加载组件之前更改菜单,因此我可以根据需要显示不同的菜单到用户登录。我用 componentWillMount 尝试过这种方式,我尝试在登录两类用户之一时设置超时。

我希望在用户登录时重定向后重新加载页面,或者在组件加载到页面之前更改变量链接的方法。

class Navbar extends Component {
state = {
links: <SignedOutLinks />
}

checkMenu() {
let links = <SignedOutLinks />;
if (this.props.toxiCookie === undefined && this.props.ajudanteCookie === undefined) {
this.setState({
links: <SignedOutLinks />
})
}
if (this.props.toxiCookie === 'loginToxiTrue' && this.props.ajudanteCookie === undefined) {
this.setState({
links: <SignedInLinksAddicts />
})
}
if (this.props.toxiCookie === undefined && this.props.ajudanteCookie === 'loginAjudanteTrue') {
this.setState({
links: <SignedInLinksAjudantes />
})
}
}

componentWillMount() {
this.checkMenu();
}


render() {
return (
<nav className="nav-wrapper orange lighten-2">
<div className="container">
<Link to='/' className='brand-logo'>Home</Link>
{this.state.links}
</div>
</nav>
);
}
}

这是我的登录表单提交处理程序之一:loginT.js

handleSubmit = (e) => {


event.preventDefault();


let data = JSON.stringify({
numero_telefone: this.state.numero_tele,
password: this.state.password
});
let url = 'http://localhost:4000/loginViciados';
const response = axios.post(url, data, { headers: { "Content-Type": "application/json" } })
.then(res => {
if (res.data.data.length === 0) {
this.setState({ failLogin: 'Num.Telefone ou Password incorrectos!' });
} else {
Cookies.set("toxi", "loginToxiTrue", { expires: 7 });
const ajudante = Cookies.get('ajudante');
Cookies.remove('ajudante');
console.log(`welcome ${res.data.data[0].nome_viciado} ${res.data.data[0].apelido}`);


this.setState({
failLogin: '',
redirect: true
})


}
})
.catch(error => console.log(error.response));

}

最佳答案

不要将链接组件置于状态。最好像这样有条件地渲染组件:

{myCondition && <MyComponent />}

在您的情况下,您面临的最大挑战(我认为我们在学习 React 时都遇到过这样的挑战)是在您的应用程序中管理全局状态。您的菜单不应该知道如何检测用户是否登录。您将需要在您的许多组件中使用该逻辑,因此您必须在各处复制您的 cookie 逻辑。

为此,您可以使用上下文或存储(Redux 是一个好的开始)。使用 Redux,您将能够与每个组件共享全局状态(用户、语言等)。

注意:另外,我认为您不应该在菜单中为每个用例创建一个组件 ;)

关于javascript - 在组件加载到页面 Reactjs 之前,我如何更改我的菜单链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60567231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com