onChange事件函数在我的React App中滞后

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

在用户注册页面上的我的应用程序中,我正在尝试检查天气,用户名已存在或我的代码不存在

checkUserName = (e) => {
this.setState({username:e.target.value});
let username = this.state.username;
db.collection("users").doc(username).get()
.then((snapshot)=>{
 if(snapshot.exists)
 {
   this.setState({usernameExistError:"show"}); *//this is classname of error div*
   this.setState({isUsernameOk:false})
   console.log(this.state.usernameExistError,this.state.isUsernameOk);
 }
 else
 {
   this.setState({usernameExistError:"hide"});
   this.setState({isUsernameOk:true})
   console.log(this.state.usernameExistError,this.state.isUsernameOk);
 }
 })
 }

[当我检查控制台时一切正常。但是问题是当我在输入中按下键时,状态用户名为空,当我键入第二个字母时,用户名状态将读取第一个字母。因此,仅当数据类似于“ EXISTINGUSERNAME” + SOME_KEY_PRESS时,才能找到现有的用户名我该如何解决...预先感谢

javascript reactjs event-handling onchange html-input
1个回答
0
投票

由于state异步发生,因此在setState()仍旧的时候就使用它。

为了解决您的问题,您应该将值设置为变量,以后再使用它:

const { target: { value: username } } = e;

this.setState({ username });
db.collection("users").doc(username).get()

// ...the rest of code 

或根据回调中的当前状态执行所有操作:

this.setState({ username: e.target.value }, () => {
  db.collection("users").doc(this.state.username).get()

  // ...the rest of code 
});

setState()异步行为的示例:

class TestComponent extends React.Component {
  state = {
    data: 1
  }
  
  onClick = () => {
    console.log(`data before set: ${this.state.data}`);
    
    const newData = this.state.data + 1;
    
    this.setState({ data: newData });
    
    console.log(`data after set: ${this.state.data}`);
    console.log(`actual current data: ${newData}`);
  }
  
  render() {
    return <div onClick={this.onClick}>Click Me!</div>;
  }
};

ReactDOM.render(<TestComponent />, document.getElementById('app'));
#app {
  cursor: pointer;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"></div>
© www.soinside.com 2019 - 2024. All rights reserved.