如何在事件内使用异步等待?

时间:2019-10-29 01:13:36

标签: javascript node.js reactjs

这是我的游戏介绍页的代码。它具有一个提交按钮和用于输入用户名的文本框。当用户写下自己的名字并按下“提交”按钮时,代码会将名字发布到json文件中,然后从json文件中获取所有数据以将其发送到页首横幅。很好但是它没有得到最后发布的用户名。我试图向getUserInfo()添加一个异步等待函数,(当我添加异步等待时console.log("userinfo: " + this.state.usersInfo)显示了每个对象),但是游戏页面没有显示,并且在控制台上出现了一个奇怪的错误:Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `preventDefault` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist().我确实已经尝试使用event.persist(),但游戏页面仍未显示。有帮助吗?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: "game",
      showInicio: false,
      userInput:"",
      usersInfo:[],
      dataPosted: false,
      head:[],
      isNew: true,
    };
    //function needs to be bound to be used in child component (NavBar.js)
    this.changePage = this.changePage.bind(this);

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  changePage(page) {

    this.setState({
      page

    });
  }

  handleChange(event) {
    this.setState({userInput: event.target.value});

  }

  async handleSubmit(event) {
    this.postUserInfo(); 
    await this.getUserInfo();
    console.log("userinfo: " + this.state.usersInfo)
    alert('Username was submitted: ' + this.state.userInput);
    event.preventDefault();
    this.setState({  
      showInicio: !this.state.showInicio 
 }); 

  }


   postUserInfo(){
    fetch("http://localhost:8080/api/users" , {
      method: "post" ,
      mode: "cors",
      headers: {
        "Content-type": "application/json",
      },
      body:JSON.stringify({username:this.state.userInput,bestattempts:0, besttime:0 })
    })

    .then((res) => res.json()) 
    .then((data => {
      console.log(data);  
      this.setState({ dataPosted: true });
    }))
    .catch((error) => {
    console.log(error);
  });
  } 

  async getUserInfo() {
    return fetch("http://localhost:8080/api/users" , {mode: "cors"})
    .then((res) => res.json())
    .then((data => {
      this.setState({ usersInfo: data})

    const _head = {
      id: "ID",
      username: "Username",
      bestattempts: "Best Attempts", 
      besttime: "Best Time",
    }
    this.setState({head:_head})}))
  }     


  render() {
    if (this.state.showInicio === false){
    return (
      <div>
      <div className="inicio">  
        <h1> Memory game </h1> 
      </div>
      <div className="iniciodentro">
        <form onSubmit={this.handleSubmit}>
        <label>
          Enter your username:
        <input type="text" value={this.state.userInput} onChange={this.handleChange} required/>
        </label>
        <input type="submit" value="Submit" />
      </form>
      </div> 
      </div>
     );
    }else{
    const { page } = this.state;
    return (
      <div className="App">
        <NavBar page={page} changePage={this.changePage} />
        <div className="App-header">
          {page === "game" && <Game dataPosted={this.state.dataPosted} username = {this.state.userInput} isNew={this.state.isNew}/>}
          {page === "leaderboard" && <LeaderBoard usersInfo={this.state.usersInfo} head={this.state.head}/>}
        </div>
      </div>
    );
  }
}
}

export default App;

1 个答案:

答案 0 :(得分:0)

简单地说,我建议 我建议将您的handleSubmit变成这样:

handleSubmit(event) {
    event.preventDefault();

    this.postUserInfo().then(()=>{

        return this.getUserInfo();

    }).then(()=>{

        console.log("userinfo: " + this.state.usersInfo)
        alert('Username was submitted: ' + this.state.userInput);
        this.setState({
            showInicio: !this.state.showInicio
        });

    });
}

,然后通过您的postUserInfogetUserInfo方法进行操作:

postUserInfo(){
    return fetch("http://localhost:8080/api/users", {
        method: "post",
        mode: "cors",
        headers: {
            "Content-type": "application/json",
        },
        body: JSON.stringify({ username: this.state.userInput, bestattempts: 0, besttime: 0 })
    })
    .then((res) => res.json())
    .then(data => {
        console.log(data);
        this.setState({ dataPosted: true });
    })
    .catch((error) => {
        console.log(error);
    })

}
getUserInfo() {
    return fetch("http://localhost:8080/api/users", { mode: "cors" })
        .then((res) => res.json())
        .then(data => { //you had a syntax mistake here: (data
            this.setState({ usersInfo: data })

            const _head = {
                id: "ID",
                username: "Username",
                bestattempts: "Best Attempts",
                besttime: "Best Time",
            }
            this.setState({ head: _head })
        })
}

由于提取API已经使用了promises,因此无需使用async / await。

出现奇怪错误的原因可能是因为您试图在异步函数中阻止preventDefault()。 是因为在第一次等待之后执行了preventDefault

感谢Bravo的澄清。