javascript - 我想在进行 axios http 请求之前 setState,但不能

标签 javascript reactjs react-native asynchronous axios

所以,我想在通过 http 请求将这些状态发送到后端之前更改我的 props 状态,但是 axios 在我的 if 语句代码执行之前发送这些状态。我不明白这个异步的事情。这是代码

login(){
    const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource';
    this.setState(()=>{
      if (this.state.email.indexOf('@') == -1){
        return {email: ''}
      } else {
        return {username: ''}
      }
    })
    axios.post(url, this.state).then(response => {
      if (response.data["message"])
        this.setState({message: response.data["message"]})
      else
        this.setState({message: response.data["token"]})
    })
  }

有人有解决办法吗?

最佳答案

你可以这样做。首先设置状态,然后完成 axios 请求。 setState 函数的第二个参数是回调。

另请参阅 react 文档:https://reactjs.org/docs/react-component.html#setstate

login(){
    const url = 'https://myapi.execute-api.ap-southeast-1.amazonaws.com/stage/resource';
    this.setState(()=>{
        if (this.state.email.indexOf('@') == -1){
            return {email: ''}
        } 
        else {
            return {username: ''}
        }
    },() => {
        axios.post(url, this.state).then(response => {
        if (response.data["message"])
            this.setState({message: response.data["message"]})
        else
            this.setState({message: response.data["token"]})
        })
    });
}

关于javascript - 我想在进行 axios http 请求之前 setState,但不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58949607/

相关文章:

java - Nashorn 脚本引擎在 Java 8 SE 嵌入式上为空

reactjs - 在 react redux 中 action 和 reducer 如何相互连接

react-native - 无法从 "mobx-react/native"解析 "node_modules/react-native-router-flux/dist/Router.js"

javascript - 找到模式并动态构建正则表达式来匹配字符串

javascript - 如何通过文本内容找到 DOM 元素?

javascript - knockout : Change observable value

reactjs - GatsbyJS + Firebase : initializeApp is not a function

javascript - 使用 React 和 Axios 从 Express API 下载文件

reactjs - 不变违规 : Tried to register two views with the same name RNCSafeAreaProvider error with @react-navigation/stack

android - 在 React native Activity 的多个实例之间共享单个 ReactInstanceManager