【问题标题】:React UseEffect Hook - value updates within hook but not within body of componentReact UseEffect Hook - 挂钩内的值更新,但不在组件主体内
【发布时间】:2020-04-06 18:02:18
【问题描述】:

我正在使用 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>
    );
}

【问题讨论】:

  • field 是从父级传递的道具,因此无法从子级更新其value。你能分享一下这个field 道具是从哪里来的吗?

标签: javascript reactjs typescript react-hooks


【解决方案1】:

你需要使用useState钩子。 value 来自 prop,如果你想用 state 改变来更新它,初始化就像 -

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

当你想更新当前值时,现在在你的使用钩子中 -

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

您可以看到currentValue 在正文中也更新了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2021-12-18
    • 2020-07-12
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多