位,而这一位正在逃离我,所以提前感谢您提供的很可能是一个简单的解决方案。
我想做的就是设置我的课程组件的状态,以便从我的API接收数组。我正在很好地访问数据,它在控制台中向我显示了四个对象的数组,但状态根本不会改变。我错过了什么?
在有人问我为什么不使用Redux之前,是因为我想先了解基本原理。
import React, { Component } from 'react';
// import axios from 'axios';
import $ from 'jquery';
class CourseIndex extends Component {
constructor(){
super();
this.state = {
courses: []
}
}
componentWillMount(){
this.getCourses();
}
componentDidMount(){
this.getCourses();
}
getCourses(){
// ============================ jquery()================================
$.ajax(({
url:'/courses',
headers: {
"Authorization": localStorage.getItem('id_token')
},
dataType: 'json',
cache: false,
success: function(data){
this.setState({
courses: data
})
}.bind(this),
error: function(xhr, status, err){
console.log(err);
}
}))
console.log(this.state);
// ============================ fetch()================================
// fetch(
// '/courses',
// {
// headers: {
// "Authorization": localStorage.getItem('id_token')
// }
// })
// .then((res) => res.json())
// .then((data) => {
// this.setState({
// courses: data
// },console.log(this.state))
// });
// ============================ axios()================================
// axios
// .get(
// '/courses',
// {
// headers: {
// "Authorization": localStorage.getItem('id_token')
// }
// }
// )
// // .then(res => console.log(res.data))
// .then(res =>
// this.setState({
// courses: res
// }, console.log(this.state))
// )
// .catch(err => console.log(err));
// console.log(this.state.courses);
// const items = this.courses.map(res => (
// <li className="list-group-item">
// <h3>{ res.name }</h3>
// </li>
// ))
}
render () {
return (
<div>
</div>
)
}
}
export default CourseIndex;
顺便说一句,很抱歉代码被注释掉了——我只是在尝试不同的调用模块。
感谢
$.ajax
是异步的,因此您不能在请求完成之前记录状态,并期望状态发生更改。setState
本身也是异步的,因此如果您想在状态更改后记录状态,可以使用setState
的第二个参数,这是一个回调函数。您当前正在直接调用console.log
,但您希望提供一个将被调用的函数。
$.ajax({
url: "/courses",
headers: {
Authorization: localStorage.getItem("id_token")
},
dataType: "json",
cache: false,
success: function(data) {
this.setState(
{
courses: data
},
() => console.log(this.state)
);
}.bind(this),
error: function(xhr, status, err) {
console.log(err);
}
});