对我来说,使用axios时经常发生此错误。我无法使用未定义的属性设置状态。尽管我得到了实际的答复。我很困惑。任何解决方案将不胜感激。
json通过axios回复
[ { main: 1, left: 0, right: 0, top: 0, bottom: 0, cid: 6, '$created': '2016-10-21T11:08:08.853Z', '$updated': '2016-10-22T07:02:46.662Z', stop: 0 } ]
code.js
import React from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; export default class Main extends React.Component{ constructor(props){ super(props); this.state = { status:[] } } componentDidMount(){ this.getdata() } getdata(){ axios.get('/getactions') .then(function (data) { console.log(data.data); this.setState({ status:data }) }) } render(){ console.log(this.state) return( <div> <button >Left</button> </div> ) } } ReactDOM.render(<Main/>,document.getElementBy Id('app'))
this标准函数中的名称通常由其 调用方式决定 ,而不是由函数创建位置决定。因此this,在回调函数中,此函数与this外部函数不同:
this
getdata(){ axios.get('/getactions') .then(function (data) { console.log(data.data); this.setState({ status:data }) }) }
但是,箭头功能在this其上下文范围内关闭,因此:
getdata(){ axios.get('/getactions') .then(data => { // <== Change is here console.log(data.data); this.setState({ status:data }) }) }