Axios React - not setting state, what am I doing wrong?

╄→尐↘猪︶ㄣ 提交于 2019-12-12 03:59:17

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/42825073/axios-react-not-setting-state-what-am-i-doing-wrong

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