Javascript 一旦改变,反应自然

Javascript 一旦改变,反应自然,javascript,reactjs,react-native,jsx,Javascript,Reactjs,React Native,Jsx,我有一个问题,当我把用户:1和密码123出现在控制台空字符串,我不明白为什么有人可以帮助我 export default class App extends React.Component { // Setting up Login Activity title. constructor(props) { super(props) this.state = { UserName: '',Userpassword: ''} this.login = this.l

我有一个问题,当我把用户:1和密码123出现在控制台空字符串,我不明白为什么有人可以帮助我

export default class App extends React.Component {

  // Setting up Login Activity title.
  constructor(props) {
    super(props)
    this.state = { UserName: '',Userpassword: ''}

    this.login = this.login.bind(this);
    this.onChange = this.onChange.bind(this)

  }


onChange(e) {
  this.setState({ [e.target.name]: e.target.value });
  console.log(this.state);
}



<TextInput

          placeholder="Enter User Name"  
       
          onChange={this.onChange}

          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}

        />

 <TextInput

     
          placeholder="Enter Password"

         
           onChange={this.onChange}
       
          underlineColorAndroid='transparent'

          style={styles.TextInputStyleClass}
          secureTextEntry={true}

        />
导出默认类App扩展React.Component{
//设置登录活动标题。
建造师(道具){
超级(道具)
this.state={UserName:'',Userpassword:''}
this.login=this.login.bind(this);
this.onChange=this.onChange.bind(this)
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
console.log(this.state);
}
我添加了我的代码控制台输出的朋友,用户:1,密码:123´

我的

问题
  • onChange
    事件没有要从
    事件中分解结构的
    name
    属性。目标
    name
    未定义,并解析为第三个键
    “”
  • React状态更新是异步的,因此您不能在更新排队的同一渲染周期中对更新状态进行控制台日志记录。请注意,所有控制台日志都是
    onChange
    事件后面的“周期”
  • 解决方案 将
    onChange
    回调函数重新构造为一个通用函数。附加到
    onChangeText
    属性,以便传递文本值,并为
    TextInput
    提供一个与其更新状态匹配的“name”值

    onChange = name => value => {
      this.setState({ [name]: value });
    }
    
    ...
    
    <TextInput
      placeholder="Enter User Name"  
      onChangeText={this.onChange('UserName')}
      underlineColorAndroid='transparent'
      style={styles.TextInputStyleClass}
    />
    
    componentDidUpdate() {
      console.log(this.state);
    }