简体   繁体   中英

React UseEffect Hook - value updates within hook but not within body of component

I'm using a font-picker-react package to render fonts using a Google Font API.
Each time a new font is selected from a dropdown, I want to use this to update a field value.
Currently, within the useEffect hook, the 'value' correctly updates. However, when console logging 'value' within the body of the component, this doesn't update and I'm not sure why.

export function FontPickerInputField<T = any>({ field }: FontPickerSidebarProps<T>) {
    const placeholderFont: string = 'Open Sans';
    const [fontFamily, setFontFamily] = useState(placeholderFont);
    let { value, name } = field;
    const fontFormat: string = fontFamily.replace(/\s/g, '+');
    const updatedFont = `https://fonts.googleapis.com/css?family=${fontFormat}:300,300i,400,400i,500,500i,700,700i,900,900i&display=swap`;
    const [googleFontLink, setGoogleFontLink] = useState(updatedFont);

    useEffect(() => {
        setGoogleFontLink(updatedFont);
        value = googleFontLink;
    }, [fontFamily]);

    return (
        <StyledContainer>
            <FontPicker
                apiKey="MY-API-KEY"
                activeFontFamily={fontFamily}
                onChange={({ family }) => setFontFamily(family)}
                limit={100}
                sort={'popularity'}
            />
        </StyledContainer>
    );
}

You need to use useState hook. value comes from the prop and if you want to update it with the state change, initialize like -

const [currentValue, setCurrentValue] = useState(value); // initialize with the value from the props

now in your use hook when you want to update current value -

useEffect(() => {
        setGoogleFontLink(updatedFont);
        setCurrentValue(googleFontLink);
    }, [fontFamily]);

You can see then currentValue is updated in body also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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