[英]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.我正在使用 font-picker-react 包来使用 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.目前,在 useEffect 钩子中,“值”正确更新。 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.您需要使用
useState
钩子。 value
comes from the prop and if you want to update it with the state change, initialize like - value
来自道具,如果你想用状态改变来更新它,初始化像 -
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.您可以看到然后
currentValue
也在 body 中更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.