【问题标题】:Why is the value of my variable not showing in the render for my react component?为什么我的变量的值没有显示在我的反应组件的渲染中?
【发布时间】:2020-05-11 19:41:15
【问题描述】:

我对 REACT 很陌生,我觉得这是一个如此简单的解决方案,但我没有找到任何可以帮助我的东西,所以我想在这里问问自己。

我有一个组件,我试图根据 location.pathname 更改文本。代码如下所示:

import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";

function PageTitle(props) {

    let location = useLocation();
    let title;

    useEffect(() => {
        let page = location.pathname;
        changeTitleState(page);
    });


    function changeTitleState(page) {
        switch (page) {
            case "/":
                title = "About Me";
                console.log("The title is " + title)
                break;
            case "/portfolio":
                title = "Portfolio";
                console.log("The title is " + title)
                break;
            case "/contact":
                title = "Contact"
                console.log("The title is " + title)
                break;
            default:
                title = "";
                break;
        }
    };

    return (
        <div className="content">
            <div className="container my-3 p-3 border border border-info bg-light">
                <div className="d-flex row">
                    <div className="align-items-baseline col-lg-12 text-info">
                        <h1 className="display-4 text-center text-lg-left">{title}</h1>
                    </div>
                </div>

                <hr className="my-3" />
                {props.children}
            </div>
        </div>
    )
};

export default PageTitle;

我有一个名为“title”的变量,它带有一个函数来切换该变量的字符串,然后在它下面的渲染中显示它。但是,它没有出现。我认为这可能是一个范围问题,但我觉得我在代码中正确地使用了这个,所以也许这是我不熟悉的 REACT 怪癖。我在这里遗漏了什么吗?

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    当 location.pathname 改变时,你需要 title 是状态和更新

    let title
    

    应该是

    const [title, setTitle] = useState('');
    

    在你的 changeTitleState 函数中调用 setTitle

     function changeTitleState(page) {
        switch (page) {
            case "/":
                setTitle("About Me");
                console.log("The title is " + title)
                break;
            case "/portfolio":
              setTitle("Portfolio");
                console.log("The title is " + title)
                break;
            case "/contact":
              setTitle("Contact");
                console.log("The title is " + title)
                break;
            default:
              setTitle("");
                break;
        }
    };
    

    【讨论】:

    • 就是这样,当然要使用state。感谢您的帮助!
    • 当然。如果此答案是您要找的,请勾选正确。
    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    • 2012-07-09
    • 2020-03-02
    相关资源
    最近更新 更多