简体   繁体   中英

Reactjs - state updating - Ajax - Axios

Im trying to update my states after a form submit, without refreshing the page. part of my ReactJs code:

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...


    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...
    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => { 
        console.log(err);
        this.setState({errorMessage: err.message});    
    })
}

but it shows the following error: Cannot read property 'setState' of undefined

Just change your code to

.then((response) => {
  // console.log(response.data); //data from the DB
  this.setState({
    json:JSON.parse(response.data)
  });
})

You're gwtting the error because when you refer to this in function you refer to whatever context this function is called in (some Promise internals). By using arrow syntax you're automatically binding it to the context it's declared in (component in your case)

It will be because your trying to acces to a method which is no defined in your response function. You have to assign this to variable before running axios. please check this out

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...


    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...


    const my_this = this;


    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      my_this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => { 
        console.log(err);
        my_this.setState({errorMessage: err.message});    
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM