React Native - setState on object inside state

僤鯓⒐⒋嵵緔 提交于 2019-12-25 08:37:12

问题


I have two text inputs on modal screen, when I'm filling first input - state is updated, and when I jump on second input and start typing - value of the first input is empty.

Here is code:

constructor(){
    super()
    this.state={
    Modal: {
        EduModalVisible: false,
        ProTitleModalVisible: false,
        PsychoModalityModalVisible: false,
    },

    User: { 
        NameOfFaculty: '',
        YearOfGraduate: '',
    }
}

}

And text input looks like this:

<TextField label={'Faculty'} highlightColor={'#76a6ef'}
        value={this.state.User.NameOfFaculty} onChangeText={(faculty) => this.setState({User: { NameOfFaculty: faculty }})} />
<TextField label={'Year Of Graduation'} highlightColor={'#76a6ef'}
        value={this.state.User.YearOfGraduate} onChangeText={(year) => this.setState({User: { YearOfGraduate: year }})} />

I think that problem is in updating state of object inside state, but I'm not sure how to solve this.


回答1:


Here's an example: https://snack.expo.io/rkeQ7cxWb

You need to assign the property for the existing object in order to preserve it contents:

onChangeText={(faculty) => {
  const User = Object.assign({}, this.state.User, { NameOfFaculty: faculty });
  this.setState({ User });
}}


来源:https://stackoverflow.com/questions/44117724/react-native-setstate-on-object-inside-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!