【发布时间】:2020-12-25 14:44:28
【问题描述】:
所以我有一个问题,我已经坚持了几个小时。我的状态没有在函数内更新。正如您在我的示例中看到的那样,我有一个 useState 钩子,它负责保持文本输入的值。假设我输入“abcd”,如果我在返回之前控制台在handleChange 和外部记录状态,状态显示正确,但是在基本上负责保存功能的handleHeaderRightButtonPress 上,它没有'不更新,它总是我的默认值,在这种情况下randomVal。任何想法为什么会发生这种行为或我该如何解决它?提前致谢:
我的例子(我去掉了不必要的代码,这样更容易)
const TextAreaScreen = ({ navigation, route }) => {
const placeholder = route.params?.placeholder;
const [value, setValue] = useState('randomval');
useEffect(() => {
navigation.setOptions({
title: route.params?.title,
headerRight: () =>
<NavigationHeader.TextButton
label={t('general.done')}
onPress={handleHeaderRightButtonPress}
/>
});
}, []);
const handleChange = (value: string) => {
console.log('here', value); //the updated value shows up correctly
setValue(value);
};
const handleHeaderRightButtonPress = () => {
const onFinish = route.params?.onFinish;
console.log('value in handleFunc', value); // the updated values does NOT work here
onFinish(value);
navigation.goBack();
};
console.log('state val::', value); // updated value shows up correctly
return (
<TextArea
value={value}
placeholder={placeholder}
onChangeText={handleChange}
/>
);
};
export default TextAreaScreen;
【问题讨论】:
-
你能展示你的
onFinish做什么吗? -
它通过 route prop 作为参数传入:
onFinish: formikProps.handleChange('description') -
您在安装组件时包含了
value的值,因此当时还包含的所有回调都将引用它们包含在同一渲染周期中的状态。当value更新时,您需要通过将其添加到效果的依赖数组中,将其值重新包含在效果中的新回调中。基本上你的问题是如何修复/解决陈旧状态。
标签: reactjs react-native react-navigation