简体   繁体   English

当 State 更改时,React 功能组件不会更新 DOM

[英]React Functional Component is not updating DOM when State Changes

I am trying to update my components but they will not update when a new value is updated in my LocalStorage.我正在尝试更新我的组件,但在我的 LocalStorage 中更新新值时它们不会更新。

Here is my code:这是我的代码:

App.js:应用程序.js:

import './App.css';
import CTA from './components/CTA';


function App() {
  return (
    <div className="App">
        <CTA />
    </div>
  );
}

export default App;

The component im having issues with:该组件存在以下问题:

The component is looking at localStorage for language selection which is true or false if true, english else, french该组件正在查看 localStorage 以进行语言选择,如果为 true,则为 true 或 false,否则为英语,法语

But the dom is not updating automatically?但是dom不会自动更新吗? It changes when I refresh though...当我刷新时它会改变......

Kinda a noob...有点菜鸟...

CTA.js CTA.js

import * as React from 'react';
import CTA_Image from '../assets/cibc-event.jpeg'
import styles from '../styles/language.module.css'
import useLocalStorage from '../util/store'
import LanguageButtons from './LanguageButtons'


export default function CTA(props) {
    const [isEnglish] = useLocalStorage('isEnglish', true);

React.useEffect(() => {
    console.log(isEnglish)
}, [isEnglish])

console.log(isEnglish)
return (
    <>
        <img src={CTA_Image} className={styles.ctaImage} alt='' />

        {isEnglish === true ? 
            <p className={styles.ctaBody}>
                English, i am english, yes
            </p>
        :   <p className={styles.ctaBody}>
                French, parle french, oui
            </p>
        }

        <LanguageButtons />
    </>
)
}

LanguageButton.js:语言按钮.js:

    import { Button } from "@mui/material"
import useLocalStorage from '../util/store'
import styles from '../styles/language.module.css'

const LanguageButtons = () => {
    const [isEnglish, setEnglish] = useLocalStorage('isEnglish', true);


    let handleLanguage = (props) => {
        setEnglish(props)

        // console.log(isEnglish)
    }
    return (
        <>
            <Button variant="contained" className={styles.languageButton} onClick={()=>handleLanguage(true)}>English</Button>
            <Button variant="contained" className={styles.languageButton} onClick={()=>handleLanguage(false)}>French</Button>
        </>
    )
}

export default LanguageButtons

This is handling the Language Change of course.这当然是处理语言更改。

store.js - useLocalStorage handling store.js - useLocalStorage 处理

    import {useState} from 'react';

// Hook
function useLocalStorage(key, initialValue) {
    // State to store our value
    // Pass initial state function to useState so logic is only executed once
    const [storedValue, setStoredValue] = useState(() => {
      if (typeof window === "undefined") {
        return initialValue;
      }
      try {
        // Get from local storage by key
        const item = window.localStorage.getItem(key);
        // Parse stored json or if none return initialValue
        return item ? JSON.parse(item) : initialValue;
      } catch (error) {
        // If error also return initialValue
        console.log(error);
        return initialValue;
      }
    });
    // Return a wrapped version of useState's setter function that ...
    // ... persists the new value to localStorage.
    const setValue = (value) => {
      try {
        // Allow value to be a function so we have same API as useState
        const valueToStore =
          value instanceof Function ? value(storedValue) : value;
        // Save state
        setStoredValue(valueToStore);
        // Save to local storage
        if (typeof window !== "undefined") {
          window.localStorage.setItem(key, JSON.stringify(valueToStore));
        }
      } catch (error) {
        // A more advanced implementation would handle the error case
        console.log(error);
      }
    };
    return [storedValue, setValue];
  }

  export default useLocalStorage;

Any help is appreciated thanks!任何帮助表示感谢! Apologies for noob question为菜鸟问题道歉

The different components' calls to useLocalStorage are not linked.不同组件对useLocalStorage的调用没有关联。 So, calling a state setter in one of them won't result in the other one seeing its state change as well.因此,在其中一个中调用 state 设置器不会导致另一个也看到其 state 更改。

Call useLocalStorage only once, in a parent component - lift state up .仅在父组件中调用useLocalStorage一次 -将 state 向上提升 Then, pass down the state value and the state setter to whatever needs it.然后,将 state 值和 state 设置器传递给任何需要的值。

export default function CTA(props) {
    const [isEnglish, setEnglish] = useLocalStorage('isEnglish', true);
    return (
        <>
            <img src={CTA_Image} className={styles.ctaImage} alt='' />

            {isEnglish === true ? 
                <p className={styles.ctaBody}>
                    English, i am english, yes
                </p>
            :   <p className={styles.ctaBody}>
                    French, parle french, oui
                </p>
            }

            <LanguageButtons {...{ setEnglish }}/>
        </>
    );
}

and then use the new props:然后使用新的道具:

const LanguageButtons = ({ setEnglish }) => (
    <>
        <Button variant="contained" className={styles.languageButton} onClick={()=>setEnglish(true)}>English</Button>
        <Button variant="contained" className={styles.languageButton} onClick={()=>setEnglish(false)}>French</Button>
    </>
);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM