[英]Reset Input Values Upon Exiting
我在我的應用程序中使用本機基本輸入字段,如下所示:
const [startingPoint, setStartingPoint] = useState('');
const [endingPoint, setEndingPoint] = useState('');
<Input
placeholder="My Input Value"
onChangeText={text => setEndingPoint(text)}
value={endingPoint}
/>
這些值包含在 View 和 Modals 中。 不是任何形式。
輸入功能本身可以正常工作。 但是,當我退出頁面(如在我的應用程序中單擊返回或取消)並返回時,我之前在字段中寫入的值仍然存在。 每次退出頁面時有什么方法可以重置它們嗎?
這就是我的模態的樣子:
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 隱藏后仍會掛載,因此數據仍會在 state 中浮動。
您可以做的是使用帶有useEffect
的效果,以便在隱藏模式時重置 state,“觀看” showJourneyDetailsPage
state,例如:
useEffect(() => {
if (showJourneyDetailsPage) return; // If shown, do nothing
setStartingPoint('');
setEndingPoint('');
// ...
}, [showJourneyDetailsPage]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.