[英]Why does my useState value reset in onPress method?
我在我的本機反應組件中使用了一個名為 tripState 的 useState。
const [tripState, setTripState] = useState<NewTripState>({
name: "",
description: "",
thumbnail: "",
});
我使用 function 在文本字段中更改其值:
const onChange = (
key: keyof NewTripState,
value: string | null,
): void => {
setTripState({
...tripState,
[key]: value,
});
};
文字輸入:
<TextInput
value={tripState.name}
onChangeText={(value: string): void => {
onChange("name", value);
}}
placeholder={"Enter trip name"}
/>
在文本輸入時調用。 如果我 console.log 中的值:
useEffect(() => {
console.log(tripState); // console.logs updated state
}, [tripState]);
它控制台記錄正確的(更新的)值,但是當我嘗試在我的onSubmit
方法中控制台記錄它時,該方法在Pressable
上的onPress
上調用,我得到了初始值。
<Pressable onPress={onSubmit}>
<Text>Save</Text>
</Pressable>
const onSubmit = () => {
console.log(tripState); // console.logs initial state
};
有人可以幫幫我嗎? 我不知道該怎么做了。
編輯 1:整個組件:
import React, { useEffect, useState } from "react";
import { useColorScheme } from "react-native";
import { getUserHoliday } from "../../api/firestore/trips";
import ProfilePicture from "../../components/ProfilePicture";
import {
View,
Text,
Pressable,
} from "../../components/Themed";
import { tintColorLight } from "../../constants/Colors";
import store from "../../redux/store";
import { getUserId } from "../../redux/stores/user";
import { Holiday } from "../../utils/types/holiday";
import { Trip } from "../../utils/types/trip";
type NewTripScreenProps = {
navigation: any;
route: any;
};
export type NewTripState = {
name: string;
description: string;
thumbnail: string;
};
const NewTripScreen = (props: NewTripScreenProps) => {
const { navigation } = props;
const [tripState, setTripState] = useState<NewTripState>({
name: "",
description: "",
thumbnail: "",
});
useEffect(() => {
console.log(tripState);
}, [tripState]);
const onChange = (
key: keyof NewTripState,
value: string | null,
): void => {
setTripState((currentValue) => ({
...currentValue,
[key]: value,
}));
};
const userId = getUserId(store.getState());
const colorScheme = useColorScheme();
useEffect(() => {
getUserHoliday(userId).then((holidays) => {
setHolidays(holidays);
});
navigation.setOptions({
headerTitle: "New Trip",
headerRight: () => (
<Pressable onPress={onSubmit}>
<Text
style={{
color: tintColorLight,
fontSize: 18,
}}
>
Save
</Text>
</Pressable>
),
headerTintColor: tintColorLight,
headerTitleStyle: {
color: colorScheme === "dark" ? "#fff" : "#000",
},
});
}, []);
const onSubmit = () => {
console.log(tripState.name);
const trip: Trip & { holiday?: Holiday | null } = {
userId: userId,
...tripState,
status: "created",
};
};
return (
<View>
<Text
style={{
fontWeight: "bold",
fontSize: 32,
padding: 10,
}}
>
New Trip
</Text>
<View style={{ alignItems: "center", marginTop: 20 }}>
<TextInput
value={tripState.name}
onChangeText={(value: string): void => {
onChange("name", value);
}}
placeholder={"Enter trip name"}
/>
<TextInput
value={tripState.description}
onChangeText={(value: string): void => {
onChange("description", value);
}}
placeholder={"Enter Description"}
style={{ marginTop: 20 }}
/>
<Text
style={{
fontWeight: "bold",
fontSize: 32,
padding: 10,
}}
>
Thumbnail
</Text>
<ProfilePicture
photoURL={tripState.thumbnail}
onPress={() => {}}
/>
</View>
</View>
);
};
export default NewTripScreen;
這是因為 useEffect 和空依賴數組而發生的。 當您在 Pressable 的 onPress 偵聽器上添加onSubmit()
時,由於 useEffect 具有空依賴數組,因此使用onSubmit
內的 tripState 的原始值。
像這樣更改代碼
useEffect(() => {
getUserHoliday(userId).then((holidays) => {
setHolidays(holidays);
});
navigation.setOptions({
headerTitle: "New Trip",
headerTintColor: tintColorLight,
headerTitleStyle: {
color: colorScheme === "dark" ? "#fff" : "#000",
},
});
}, []);
useEffect(() => {
navigation.setOptions({
headerRight: () => (
<Pressable onPress={onSubmit}>
<Text
style={{
color: tintColorLight,
fontSize: 18,
}}
>
Save
</Text>
</Pressable>
)
});
}, [tripState]);
您要查找的主題稱為“過時值”。 當值被鎖定到您的 function 並且不刷新時,就會發生這種情況。 React useState 有辦法解決這個問題,非常簡單:
代替:
setTripState({
...tripState,
[key]: value,
});
告訴 setState 你想使用最新的值:
setTripState(currentValue => ({
...currentValue,
[key]: value,
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.