反应性句柄更新输入未定义

问题描述 投票:0回答:1

我的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>
react-native put
1个回答
0
投票

也许您应该添加一个值来控制文本显示?

<TextInput
    style={styles.inputText}
    placeholder="First Name"
    placeholderTextColor="#003f5c"
    defaultValue={route.params.user.firstname}
    onChangeText={(firstname) => setFirstname(firstname)}
    value={firstname}  // Here~~~~ \OwO/
/>

DOC

PS:由于您的api中的设置setFirstname仅设置为firstname,而不显示firstname,因此onChangeText是您触发editing the textinput时的事件,因此您需要value使其显示为您想要的内容显示。

更新

尝试此

import React, { useCallback } from "react";
  const handleUpdate = useCallback(async () => {

    ...

  }, [])

  useEffect(() => {
    handleUpdate()
  }, [handleUpdate])
© www.soinside.com 2019 - 2024. All rights reserved.