Axios React - not setting state, what am I doing w

2019-09-15 17:36发布

So here's the code, I simply want to use axios to get, then set that response to the state. Using ES6 arrow functions

import React, { Component } from 'react';
import './App.css';
import axios from 'axios';

class FieldValues extends Component {
  constructor (props){
    super(props);
      this.state = {
        todos: []
      }
  }
  componentDidMount() {
    axios.get(`127.0.0.1:8000/api/todos/`)
      .then(res => {
        this.setState({res.data});
      });
  }

  render(){
    console.log(this.state);

  }
}

export default FieldValues;

Here's a browser screenshot from my local host serving up json via express and node.

screenshot

And my error - Is it sad to admit that I've been at this for hours now?

Failed to compile.

Error in ./src/App.js Syntax error: Unexpected token, expected , (15:26)

  13 |     axios.get(`127.0.0.1:8000/api/todos/`)
  14 |       .then(res => {
> 15 |         this.setState({res.data});
     |                           ^
  16 |       });
  17 |   }
  18 | 

Error
 @ ./src/index.js 13:11-27

标签: reactjs axios
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-15 17:50

I'm guessing what you're getting back from your API is an array of ToDos. In that case, you need this:

this.setState({todos: res.data});

The setState call takes in an object. When creating an object, you need to give each property a name and a value. The way you're doing it, you're not giving your property a name. Perhaps you've seen code like this and that's causing confusion:

let name = "John";
let obj = {name};

The reason THAT works is because in ES6 they added a feature where if your variable name also happens to be the name you want as your property name, you can omit the {name: name} duplication. In your case however, A) it's a nested property of res so that trick wouldn't work, and B) you want it to be called todos.

查看更多
登录 后发表回答