简体   繁体   English

React - 当我的 React 钩子更新时,我的用户界面无法正确重新渲染

[英]React - My user interface does not re-render properly when my React hook is updated

I created a site that is bilingual - English and Spanish.我创建了一个双语网站——英语和西班牙语。 In the navigation menu there are two buttons for the user to switch between the languages.在导航菜单中有两个按钮供用户在语言之间切换。 By default, my site displays all of the text in English.默认情况下,我的网站以英文显示所有文本。

I'm using React hooks to update between the two languages.我正在使用 React 钩子在两种语言之间进行更新。 It's a lot of code so I'm only going to display the relevant parts.代码很多,所以我只显示相关部分。

Index.js索引.js
Inside of Index.js I have my React hook and useState is being implemented to call either the updateLanguageToEnglish or updateLanguageToSpanish functions depending on if the user pressed the English or Spanish button in the navigation menu.在 Index.js 内部,我有我的 React 钩子,并且 useState 被实现来调用updateLanguageToEnglishupdateLanguageToSpanish函数,具体取决于用户是否按下导航菜单中的英语或西班牙语按钮。

    // Language database & state
        const english = languageDatabase.english;
        const spanish = languageDatabase.spanish;
        var [language, setLanguage] = useState(english);
        const updateLanguageToEnglish = () => setLanguage(english);
        const updateLanguageToSpanish = () => setLanguage(spanish);


 {/* Travel Information */}
            <TravelInformation
                title={language.travelInformationTitle}
                airport={language.travelInformationAirport}
                passport={language.travelInformationPassport}
                exchange={language.travelInformationExchange} />

NavigationBar.js导航栏.js

const NavigationBar = (props) => {

    const menuBars = <FontAwesomeIcon icon={faBars} />

    return (
        <Navbar collapseOnSelect fixed="top" expand="xl" variant="dark" className="animate__animated animate__fadeInDown animate__delay-1s langWrap">
            <Navbar.Toggle aria-controls="responsive-navbar-nav">
                <span className="fa-bars">{menuBars}</span>
                <span>MENU</span>
            </Navbar.Toggle>
            <Navbar.Collapse id="responsive-navbar-nav">
                <Nav className="m-auto">
                    <Nav.Link href="#rsvp">RSVP</Nav.Link>
                    <Nav.Link href="#ceremony">{props.ceremony}</Nav.Link>
                    <Nav.Link href="#venue">{props.venue}</Nav.Link>
                    <Nav.Link href="#hotels">{props.hotels}</Nav.Link>
                    <Nav.Link href="#travel-information">{props.travelInformation}</Nav.Link>
                    <Nav.Link href="#faqs">{props.faq}</Nav.Link>
                    <Navbar.Text id="nav-divider">|</Navbar.Text>
                    <div className="dropdown-divider"></div>
                    <Nav.Link onClick={props.updateLanguageToEnglish} href="javascript:void(0)">English</Nav.Link>
                    <Nav.Link onClick={props.updateLanguageToSpanish} href="javascript:void(0)">Español</Nav.Link>
                </Nav>
            </Navbar.Collapse>
        </Navbar>
    )
}
export default NavigationBar

languageDatabase.js语言数据库.js
languageDatabase.js is just an object with 2 more objects inside of it, one for the English text and the second for the Spanish text. languageDatabase.js 只是一个 object 内部还有 2 个对象,一个用于英文文本,第二个用于西班牙文文本。

import * as React from 'react';

const DOS_website_english = <a href="https://travel.state.gov/content/travel/en/passports.html" target="_blank" rel="noopener noreferrer">website</a>
const DOS_website_espanol = <a href="https://travel.state.gov/content/travel/en/passports.html" target="_blank" rel="noopener noreferrer">sitio web</a>
const exchange_english = <a href="https://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=MXN" target="_blank" rel="noopener noreferrer">exchange rate</a>
const exchange_spanish = <a href="https://www.xe.com/currencyconverter/convert/?Amount=1&From=USD&To=MXN" target="_blank" rel="noopener noreferrer">tipo de cambio</a>

const data = {
    "english": {
        //NavBar
        "navCeremony": "Ceremony",
        "navReception": "Reception",
            "navVenue": "Venue",
            "navThingsToDo": "Things to do in Morelia",
        "navHotels": "Hotels",
        "navTravelInformation": "Travel Information",
        "navFAQ": "FAQs",

        //Travel Information
        "travelInformationTitle": "Travel Information",
        "travelInformationAirport": "General Francisco Mujica International Airport",
        "travelInformationPassport": <>In order to travel to Mexico, you will need a valid U.S. passport. If you do not have one or if it has expired, please take the necessary steps to obtain or renew your passport. Please visit the U.S. Department of State's {DOS_website_english} for more information.</>,
        "travelInformationExchange": <>The currency in Mexico is the Peso and the {exchange_english} is usually around $20 MXN for $1 USD.</>,
    },
    "spanish": {
        //NavBar
        "navCeremony": "Ceremonia",
        "navReception": "Recepción",
            "navVenue": "El Lugar",
            "navThingsToDo": "Qué hacer en Morelia",
        "navHotels": "Hoteles",
        "navTravelInformation": "Información Para Viajar",
        "navFAQ": "Preguntas Frecuentes",

        //Travel Information
        "travelInformationTitle": "Información Para Viajar",
        "travelInformationAirport": "Aeropuerto Internacional General Francisco Mujica",
        "travelInformationPassport": <>Para ciudadanos de Estados Unidos y poder viajar a México es necesario un Pasaporte Estadounidense. Tendrá que obtener uno y tomar las medidas necesarias para obtenerlo o renovarlo. Por favor visite el {DOS_website_espanol} del Departamento de Estado de EE. UU. para más información.</>,
        "travelInformationExchange": <>La moneda en México es el peso y el {exchange_spanish} es generalmente alrededor de $20 MXD por $1 USD.</>,
    }
}

export default data;

The problem I'm having is that there are parts of my site that don't re-render properly when switching between the languages.我遇到的问题是我的网站的某些部分在切换语言时无法正确重新呈现。 I'm attaching an image to show as an example.我附上一张图片作为示例。 Another issue is that the text will re-render but it'll be a mix of English and Spanish and the text just looks distorted.另一个问题是文本会重新呈现,但它会混合使用英语和西班牙语,并且文本看起来会失真。
This is only happening in certain sections of the page and weirdly enough only on my phone and iPad.这仅在页面的某些部分发生,而且奇怪的是仅在我的手机和 iPad 上发生。 It works perfectly fine on Desktop.它在桌面上运行良好。


I feel like my code is straightforward and I'm not understanding why the text updates properly on most of the site but not in 2-3 sections.我觉得我的代码很简单,我不明白为什么大多数网站上的文本都能正确更新,但不能在 2-3 部分中正确更新。 Any help or guidance would be greatly appreciated.任何帮助或指导将不胜感激。

在此处输入图像描述

在此处输入图像描述

Because you need to always ensure entire DOM tree is re-rendered when the language is updated, I would suggest to add "key" prop to the TravelInformation component.因为您需要始终确保在更新语言时重新渲染整个 DOM 树,所以我建议将“key”道具添加到 TravelInformation 组件。

Like -喜欢 -

<TravelInformation
    key="english"
    title={language.travelInformationTitle}
    airport={language.travelInformationAirport}
    passport={language.travelInformationPassport}
    exchange={language.travelInformationExchange}
/>

You can either specify key = english or spanish.您可以指定 key = 英语或西班牙语。

This can be part of your languageDatabase.js, like -这可以是您的 languageDatabase.js 的一部分,例如 -

const data = {
    "english": {
        "key": "english-lang",
        //NavBar
        "navCeremony": "Ceremony",
        "navReception": "Reception",
            "navVenue": "Venue",
            "navThingsToDo": "Things to do in Morelia",
        "navHotels": "Hotels",
        "navTravelInformation": "Travel Information",
        "navFAQ": "FAQs",

        //Travel Information
        "travelInformationTitle": "Travel Information",
        "travelInformationAirport": "General Francisco Mujica International Airport",
        "travelInformationPassport": <>In order to travel to Mexico, you will need a valid U.S. passport. If you do not have one or if it has expired, please take the necessary steps to obtain or renew your passport. Please visit the U.S. Department of State's {DOS_website_english} for more information.</>,
        "travelInformationExchange": <>The currency in Mexico is the Peso and the {exchange_english} is usually around $20 MXN for $1 USD.</>,
    },
    "spanish": {
        "key": "spanish-lang",
        //NavBar
        "navCeremony": "Ceremonia",
        "navReception": "Recepción",
            "navVenue": "El Lugar",
            "navThingsToDo": "Qué hacer en Morelia",
        "navHotels": "Hoteles",
        "navTravelInformation": "Información Para Viajar",
        "navFAQ": "Preguntas Frecuentes",

        //Travel Information
        "travelInformationTitle": "Información Para Viajar",
        "travelInformationAirport": "Aeropuerto Internacional General Francisco Mujica",
        "travelInformationPassport": <>Para ciudadanos de Estados Unidos y poder viajar a México es necesario un Pasaporte Estadounidense. Tendrá que obtener uno y tomar las medidas necesarias para obtenerlo o renovarlo. Por favor visite el {DOS_website_espanol} del Departamento de Estado de EE. UU. para más información.</>,
        "travelInformationExchange": <>La moneda en México es el peso y el {exchange_spanish} es generalmente alrededor de $20 MXD por $1 USD.</>,
    }
}

And then you can update your code like -然后你可以更新你的代码,比如 -

<TravelInformation
    key={language.key}
    title={language.travelInformationTitle}
    airport={language.travelInformationAirport}
    passport={language.travelInformationPassport}
    exchange={language.travelInformationExchange}
/>

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

相关问题 React Native for Web:当 state 更新时,我的组件不会重新渲染 - React Native for Web: My component does not re-render when state is updated 为什么在获取数据后更新 props 中传递的数组时,我的 React 子组件不会重新渲染? - Why does my React child component not re-render when an array passed down in props is updated after data fetch? 反应:上下文的变化不会重新渲染我的组件 - react : changes on context does not re-render my components 当我的“useState”不断更新时,React 重新渲染 - React re-render when my “useState” constant updates 当父组件重新渲染时,react hook 组件会重新渲染吗? - Does react hook component re-render when parent component re-renders? 当 state 更新时,组件不会使用更新的 state 重新渲染(反应) - When state is updated, component does not re-render with updated state (REACT) React Hook:useState 的 set 函数不会触发重新渲染 - React Hook: The set function of useState does not trigger re-render React 不会重新渲染更新后的数组 state - React does not re-render updated array state 子组件更新时反应不重新渲染 - React not re-render when child component updated React没有使用useState钩子触发重新渲染 - React not triggering re-render with useState hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM