如何从 parsedJSON 中获取数据 reactJS

How to get data from parsedJSON reactJS

我在这里使用 ReactJS 设置了一个基本的 WebApp。现在我可以使用 POST 请求将数据添加到我的数据库,没问题,我的后端响应向我发送了一个 JSON,其中包含我传递的所有数据和数据库中的 _id。我需要获取此 _id 并将其保存在我的状态中,以便我可以将其传递到我的 WebApp 中的下一个 URL。那是我的 POST 请求的代码:

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => console.log(parsedJSON._id))
      .catch(error => alert('Check your data', error))
      .then(this.props.history.push('/get')) // change page layout and URL
    }
    console.log(this.state.id); //debug to see if the _id is saved in my state
  }

这是我的构造函数:

  constructor(props){
    super(props);
    this.state={
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:'',
      id:''
    }
  }

我尝试在 parsedJSON 之后调用一个使用 this.setState() 的函数,使用 function(parsedJSON){this.state.id : parsedJSON._id}。我试过这样的新功能:

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

并将 .then(parsedJSON => console.log(parsedJSON._id)) 更改为 .then(parsedJSON => this.cahngeID(parsedJSON))。但是 none 然后工作...

我用 .then(parsedJSON => console.log(parsedJSON._id)) 留下了代码,这样可以确保我可以看到这个值,并且在我的控制台中它打印得很好。

这是我的后端发送的响应示例:{"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

如何从我的回复中获取“_id”?

您不应该直接触摸 this.state 属性。如果您这样做,React 将抛出错误,因为 React 需要知道 this.state 何时更新,以便它可以跟踪更改。如果您直接操作 属性 则无法执行此操作。这就是为什么我们有 React.Component#setState。 "shallow" 版本是最常用的,您可以在其中传递一个将合并到您的状态中的对象。例如,以下内容:

.then(parsedJSON => this.setState({ id: parsedJSON._id }))

相当于:

Object.assign(this.state, { id: parsedJSON._id });

除了 React 会跟踪状态何时更新。

请注意,setState 也是异步的,并将回调作为第二个参数。你可以 read more about that here.

根据下面的评论,

在构造函数的末尾添加这行代码:

this.SubmitClick = this.SubmitClick.bind(this);

因为 JavaScript 没有将 'this' 的实例值绑定到我们的方法。