Axios React-未设置状态,我在做什么错? [英] Axios React - not setting state, what am I doing wrong?
问题描述
所以这是代码,我只是想使用axios来获取,然后将该响应设置为状态.使用ES6箭头功能
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;
这是我的本地主机上的浏览器屏幕快照,它通过express和node提供json.
Here's a browser screenshot from my local host serving up json via express and node.
和我的错误 - 它是可悲的承认,我已经在这几个小时,现在
And my error - Is it sad to admit that I've been at this for hours now?
无法编译.
./src/App.js中的错误 语法错误:意外令牌,应为(15:26)
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
推荐答案
我猜想您从API中获得的回报是一个ToDos数组.在这种情况下,您需要这样做:
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});
setState
调用接受一个对象.创建对象时,需要为每个属性指定一个名称和一个值.这样做的方式是不给您的财产起名字.也许您已经看到了这样的代码,并且引起了混乱:
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};
之所以起作用,是因为他们在ES6中添加了一项功能,即如果您的变量名也恰好是您想要用作属性名的名称,则可以省略{name: name}
重复项.但是,在您的情况下,A)是res
的嵌套属性,因此该技巧将不起作用,并且B)您希望将其称为todos
.
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
.
这篇关于Axios React-未设置状态,我在做什么错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!