![](/img/trans.png)
[英]State Value Stops Updating Within UseEffect Hook - Gatsby/React
[英]React UseEffect Hook - value updates within hook but not within body of component
我正在使用 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>
);
}
您需要使用useState
鈎子。 value
來自道具,如果你想用狀態改變來更新它,初始化像 -
const [currentValue, setCurrentValue] = useState(value); // initialize with the value from the props
現在在您想要更新當前值時使用鈎子 -
useEffect(() => {
setGoogleFontLink(updatedFont);
setCurrentValue(googleFontLink);
}, [fontFamily]);
您可以看到然后currentValue
也在 body 中更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.