简体   繁体   English

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

[英]how do i change my menu links before component is loaded to page Reactjs

I am trying to change the menu before the component loads, so i can display a diferent menu according to the user login.我试图在组件加载之前更改菜单,因此我可以根据用户登录显示不同的菜单。 I have tried this way with componentWillMount, I have tried setting timeouts when i login one of the two categories of users.我已经用 componentWillMount 尝试过这种方式,当我登录两类用户之一时,我尝试设置超时。

I would like to either have the page reload after I redirect a user when he logs in or a way to change the variable links before the components loads to the page.我想在用户登录时重定向用户后重新加载页面,或者在组件加载到页面之前更改变量链接。

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>
    );
}
}

This is one of my logins form submit handler:loginT.js这是我的登录表单提交处理程序之一: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));

}

Do not put your links component in state.不要将您的链接组件置于状态。 It's better to conditionally render component like this :最好像这样有条件地渲染组件:

{myCondition && <MyComponent />}

In your case, the biggest challenge you have (and we all had that challenge while learning React I think) is to manage global state in your app.就您而言,您遇到的最大挑战(我认为我们在学习 React 时都遇到过这个挑战)是管理应用程序中的全局状态。 You menu should not know how to detect if the user is logged in or not.您的菜单不应该知道如何检测用户是否已登录。 You'll need that logic in a lot of your component so you'll have to duplicate your cookie logic everywhere.您将需要在很多组件中使用该逻辑,因此您必须在任何地方复制 cookie 逻辑。

To achieve this, you could use context or a store (Redux is a good start).为此,您可以使用上下文或存储(Redux 是一个好的开始)。 With Redux, you would be able to share global state (user, language, etc) to every components.使用 Redux,您将能够与每个组件共享全局状态(用户、语言等)。

NOTE : Also, I don't think you should create one component per use case in your menu ;)注意:另外,我认为您不应该在菜单中为每个用例创建一个组件;)

Did you try using componentDidUpdate?您是否尝试过使用 componentDidUpdate? this should catch if those props change.如果这些道具发生变化,这应该会抓住。

  componentDidUpdate (prevProps) {
    const { toxiCookie, ajudanteCookie } = this.props;
    if (prevProps.toxiCookie !== toxiCookie || prevProps.ajudanteCookie !== ajudanteCookie) {
      this.checkMenu();
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在页面加载之前更改 HTML 中脚本标记中的变量? - How do I change a variable in a script tag in HTML before the page has loaded? 如何获得自定义的右键单击上下文菜单以显示指向我网站上页面的两个链接? - How do I get a custom right-click context menu to show two links to a page on my site? React.js:在组件安装之前如何获取要加载的数据? - Reactjs: How to fetch data to loaded before the component is mounted? 如何在加载页面之前提交ajax请求 - How do i submit an ajax request before the page is loaded 在反应中加载页面之前,我如何调用 function - How do i call function before page is loaded in react Ajax已加载页面的一部分-如何使已加载内容中的链接正常工作? - Ajax loaded part of a page - how do I make links in the loaded content work? 我的PlayFramework Action在Future准备就绪之前返回,如何更新网页组件? - My PlayFramework Action returns before a Future is ready, how do I update a web page component? 如何在条件中添加 2 个链接? ReactJS - How do I add 2 links in condition? ReactJS 如何在reactjs中添加路由器链接 - How do I add router links in reactjs 如何使我的网站预加载器在它消失之前持续 3 秒,即使页面已加载(至少停留 3 秒) - How do I make my websites preloader last 3 seconds before it dissapears, even if the page has loaded (stays for a minimum of 3 seconds)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM