state undefined: while sending post request from react app

落花浮王杯 提交于 2021-01-29 04:54:47

问题


I am new in react and trying to send post request to an api and getting state undefined while sending post request from react app, i this occurs because state stores data as an object. Dont know how to solve this. i would really appreciate some help.

compmonent.js

import React, { Component } from 'react'

class Register extends Component {

  register () {
    // alert('register')
    console.warn('state', this.state)
    fetch('http://localhost:8000/api/v1/accounts/registration/', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(this.state)
    }).then((result) => {
      result.json().then((resp) => {
        console.log(resp.data.token)
        localStorage.setItem('register', JSON.stringify(resp.data.token))
      })
    })
  }

  render () {
    return (
      <div>

        <div>
          <label>Email</label>
          <input
            type='text' placeholder='email'
            onChange={(e) => { this.setState({ email: e.target.value }) }}
          /><br /><br />

          <label>First name</label>
          <input
            type='text' placeholder='first name'
            onChange={(e) => { this.setState({ first_name: e.target.value }) }}
          /><br /><br />

          <label>Last name</label>
          <input
            type='text' placeholder='last name'
            onChange={(e) => { this.setState({ last_name: e.target.value }) }}
          /><br /><br />

          <label>Password</label>
          <input
            type='password' placeholder='password'
            onChange={(e) => { this.setState({ password1: e.target.value }) }}
          /><br /><br />

          <label>Confirm password</label>
          <input
            type='password' placeholder='confirm password'
            onChange={(e) => { this.setState({ password2: e.target.value }) }}
          /><br /><br />

          <button onClick={() => this.register()}>Register</button>
        </div>

      </div>

    )
  }
}

export default Register

thanks


回答1:


Your code looks ok,

I've created a runnable code snippet from your code, only time state is null and not undefined, is when you don't fill-up the form and submit,

for that you can put a condition before making fetch request.


You can run the below code snippet and check :

class App extends React.Component {

register () {
    // alert('register')
    console.warn('state', this.state)
    if (this.state) { // <------ HERE
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          // Accept: 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(this.state)
      }).then((result) => {
        result.json().then((resp) => {
          console.log(resp.data.token)
          localStorage.setItem('register', JSON.stringify(resp.data.token))
        })
      })    
    }

  }

  render () {
    return (
      <div>

        <div>
          <label>Email</label>
          <input
            type='text' placeholder='email'
            onChange={(e) => { this.setState({ email: e.target.value }) }}
          /><br /><br />

          <label>First name</label>
          <input
            type='text' placeholder='first name'
            onChange={(e) => { this.setState({ first_name: e.target.value }) }}
          /><br /><br />

          <label>Last name</label>
          <input
            type='text' placeholder='last name'
            onChange={(e) => { this.setState({ last_name: e.target.value }) }}
          /><br /><br />

          <label>Password</label>
          <input
            type='password' placeholder='password'
            onChange={(e) => { this.setState({ password1: e.target.value }) }}
          /><br /><br />

          <label>Confirm password</label>
          <input
            type='password' placeholder='confirm password'
            onChange={(e) => { this.setState({ password2: e.target.value }) }}
          /><br /><br />

          <button onClick={() => this.register()}>Register</button>
        </div>

      </div>

    )
  }
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>


来源:https://stackoverflow.com/questions/62278812/state-undefined-while-sending-post-request-from-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!