我在应用程序中使用本地基本输入字段,如下所示:
const [startingPoint, setStartingPoint] = useState('');
const [endingPoint, setEndingPoint] = useState('');
<Input
placeholder="My Input Value"
onChangeText={text => setEndingPoint(text)}
value={endingPoint}
/>
这些值包装在视图和模态中。没有任何表格。
输入功能本身正常工作。但是,当我退出页面(如在我的应用程序中单击“后退”或“取消”)并返回时,我之前在字段中编写的值仍然存在。每次退出页面时,有什么方法可以重置它们吗?
这是我的模态看起来像:
export const JourneyDetailsPage: React.FunctionComponent<JourneyDetailsPageProps> = ({
toggleShowPage,
showJourneyDetailsPage,
}) => {
const [startingPoint, setStartingPoint] = useState('');
const [endingPoint, setEndingPoint] = useState('');
const [showAvailableTripsPage, setShowAvailableTripsPage] = useState(false);
const toggleAvailableTripsPage = () => {
setShowAvailableTripsPage(showAvailableTripsPage ? false : true);
};
return (
<Modal
visible={showJourneyDetailsPage}
animationType="slide"
transparent={true}>
<SafeAreaView>
<View style={scaledJourneyDetailsStyles.container}>
<View style={scaledJourneyDetailsStyles.searchTopContainer}>
<View style={scaledJourneyDetailsStyles.searchTopTextContainer}>
<Text
onPress={toggleShowPage}>
Cancel
</Text>
<Text>
Location
</Text>
<Text>
Done
</Text>
</View>
<View>
<Item rounded style={scaledJourneyDetailsStyles.searchField}>
<Icon
name="map-marker"
color="green"
/>
<Input
placeholder="Start"
onChangeText={text => setStartingPoint(text)}
value={startingPoint}
/>
</Item>
<Item style={scaledJourneyDetailsStyles.searchField}>
<Icon
name="search"
color="blue"
/>
<Input
placeholder="End"
onChangeText={text => setEndingPoint(text)}
value={endingPoint}
/>
</Item>
</View>
<View style={scaledJourneyDetailsStyles.offerContainer}>
<Text style={scaledJourneyDetailsStyles.offerText}
onPress={() =>
setShowAvailableTripsPage(true)
}
>Go</Text>
<Text style={scaledJourneyDetailsStyles.offerText}>1 Person</Text>
</View>
</View>
<AvailableTripsPage
showAvailableTripsPage={showAvailableTripsPage}
toggleShowPage={toggleAvailableTripsPage}
/>
</View>
</SafeAreaView>
</Modal>
);
};
Modal隐藏后仍会挂载,因此数据仍会在该状态下浮动。
[您可以做的是在useEffect
上使用效果,以便在模式被隐藏时重置状态,“监视” showJourneyDetailsPage
状态,例如:
useEffect(() => {
if (showJourneyDetailsPage) return; // If shown, do nothing
setStartingPoint('');
setEndingPoint('');
// ...
}, [showJourneyDetailsPage]);