onChangeText + setState不使用深度合并更新对象值

时间:2020-03-22 04:29:05

标签: javascript reactjs react-native

我试图通过设置组件的状态来更新组件的状态,但是即使在触发onChangeText之后,我的文本也没有更新。

export default class Register extends React.Component {

    constructor(props) {
        super(props)
        this.state = {

             newUser: {
                id: "",
                first_name: "Tom",
                last_name: "",
                email: "",
                age: 0,
                gender: "",
                classification: "",
                major: "",
                interest_tags: new Set()
            }

        }
    }

    updateUser = (text) =>{

    }
    render() {

        return (

            <View style={styles.container}>
                <View style={styles.welcome}>
                    <Text style={styles.welcomeText}>Enter your information below:</Text>
                    </View>
                <View style={styles.inputView}>
                    <TextInput
                                style={styles.inputText}
                                placeholder='First Name'
                                placeholderTextColor='#34415e'
                                autoCapitalize='none'
                                onChangeText={(text) => this.setState({
                                    ...this.state.newUser,
                                    first_name: text
                                    }), () => {console.log(this.state.newUser.first_name)}}

                    />

                </View>

无论我将回调函数放在updateUser函数还是在render函数中,我都无法更新Tom的first_name值。我在这里做什么错了?

3 个答案:

答案 0 :(得分:0)

您可以尝试

onChangeText={(text) => this.setState({
      newUser : {
         ...this.state.newUser,
         first_name: text,
      }
}), () => {console.log(this.state.newUser.first_name)}

答案 1 :(得分:0)

“使用检查员,卢克!” 〜Obi Wan Reactnobi

在您的setState通话中,您正在将newUserfirst_name的内容都合并到状态本身,而不是状态的newUser字段中。因此,更新后,您将获得以下状态的数据:

{
  newUser: { /* the initial value*/ },

  // all the other proprerties inside `newUser`, such as
  email: "",
  age: 0,

  // then the key you merged into the state explicitly:
  first_name: "whatever the user typed"
}

您可能打算这样写(请记住,setState已经是浅表合并,因此,如果状态对象中有更多值,则只会更新newUser

this.setState({
  newUser: {
    ...this.state.newUser,
    first_name: text
  }
})

答案 2 :(得分:0)

首先,您必须仅使用根对象更新状态

您不能像这样更新状态

onChangeText={(text) => this.setState({
                            ...this.state.newUser,
                            first_name: text
                            }), () => {console.log(this.state.newUser.first_name)}}

让我为此提供自定义功能。

updateObject = (oldObject, updatedProperties) => {
return {
    ...oldObject,
    ...updatedProperties
};};

您可以这样使用

 onChangeText={(text) => {
       let updatedFormElement ;
        updatedFormElement = this.updateObject(this.state.newUser, {
            first_name: text
        });
        this.setState({ newUser: updatedFormElement });
    }}