我的PUT
请求代码。无法更新我的名字总是说不确定。我的api正常工作。
const [firstname, setFirstname] = useState('');
const id = route.params.user._id;
const handleUpdate = async (props) => {
const token = await AsyncStorage.getItem('token');
fetch(USER_API + `${id}`, {
method: "PUT",
headers: new Headers({
Authorization: 'Bearer ' + token,
}),
body: JSON.stringify({
"firstname": firstname,
})
})
.then(res => res.json())
.then((data) => {
try {
setFirstname(data.firstname);
} catch (error) {
console.log('error', error);
}
});
}
useEffect(() => {
handleUpdate();
}, []);
我的视图布局
<View style={styles.viewContainer}>
<Text style={styles.headerText}>Edit info</Text>
<View style={styles.inputView}>
<TextInput
style={styles.inputText}
placeholder="First Name"
placeholderTextColor="#003f5c"
defaultValue={route.params.user.firstname}
onChangeText={(firstname) => setFirstname(firstname)}
/>
</View>
<TouchableOpacity style={styles.loginBtn} onPress={() => handleUpdate(props)}>
<Text style={styles.loginTextBtn}>SAVE</Text>
</TouchableOpacity>
</View>
也许您应该添加一个值来控制文本显示?
<TextInput
style={styles.inputText}
placeholder="First Name"
placeholderTextColor="#003f5c"
defaultValue={route.params.user.firstname}
onChangeText={(firstname) => setFirstname(firstname)}
value={firstname} // Here~~~~ \OwO/
/>
PS:由于您的api中的设置setFirstname
仅设置为firstname
,而不显示firstname
,因此onChangeText
是您触发editing the textinput
时的事件,因此您需要value
使其显示为您想要的内容显示。
更新
尝试此
import React, { useCallback } from "react";
const handleUpdate = useCallback(async () => {
...
}, [])
useEffect(() => {
handleUpdate()
}, [handleUpdate])