constructor(props) {
super(props);
this.state = {
data: [],
}
}
componentWillMount() {
axios.get('url here', {
auth: {
username: ' ',
password: ' '
}
}).then(function(response) {
console.log(response.data.value)
this.setState({
data: response
})
}).catch(function(error) {
console.log(error)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<ul>
{ this.state.data.map(person => <li>{person.name}</li>)}
</ul>
</div>
);
}
}
运行我的componentWillMount
时,控制台日志准确地打印出我想要的内容。但是,在我的setState
中,它说的是Cannot read property 'setState' of undefined even though it's defined
。尽管定义了data
,为什么会出现此错误?
答案 0 :(得分:2)
这是因为this
内部的.then(function() {})
是不同的。尝试.then(function() {}.bind(this))
或通过箭头功能
axios.get('url here', {
auth: {
username: ' ',
password: ' '
}
}).then(response=>{
console.log(response.data.value)
this.setState({
data: response
})
}
).catch(error=>{
console.log(error)
})
演示代码:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/todos").then(
function(resp) {
console.log(resp);
this.setState({ data: resp.data });
}.bind(this)
);
}
render() {
return (
<ul>
{this.state.data.map(todo => <li key={todo.id}>{todo.title}</li>)}
</ul>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>