React UseEffect Hook-挂钩内的值更新,但不在组件主体内

时间:2019-12-13 09:49:41

标签: javascript reactjs typescript react-hooks

我正在使用font-picker-react程序包来使用Google Font API呈现字体。
每次从下拉列表中选择一种新字体时,我都想使用它来更新字段值。
当前,在useEffect挂钩中,“值”正确更新。但是,当控制台在组件主体中记录“值”时,此消息不会更新,我不确定为什么。

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

1 个答案:

答案 0 :(得分:3)

您需要使用useState挂钩。 value来自道具,如果您想通过状态更改对其进行更新,请像-

一样进行初始化
const [currentValue, setCurrentValue] = useState(value); // initialize with the value from the props

现在,当您想更新当前值时就可以使用它-

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

您会看到currentValue的正文也随之更新。