【发布时间】:2018-05-17 12:52:42
【问题描述】:
我是 React JS 的新手。我已经阅读了一些关于如何在 Reactjs 中创建客户端休息的示例。
我的问题 - 我获得了所有课程,然后我希望为每门课程调用另一个 HTTP 服务。我的代码如下。
export default class Courses extends Component{
constructor(props) {
super(props);
this.state = {courses: []};
}
componentDidMount() {
axios.get('http://localhost:8065/api/course/all')
.then(response => {
const courseList = response.data.map(c => {
return {
id: c.id,
name: c.name,
previewBase64:c.previewBase64,
authors:
axios.get('http://localhost:8065/api/course/getAuthorsByCourseId/'+c.id+"/")
.then(res => {
const profiles = res.data.map(p => {
return {
name: p.name
};
})
})
};
})
console.log(courseList);
const newState = Object.assign({}, this.state, {
courses: courseList
});
// store the new state object in the component's state
this.setState(newState);
});
};
render(){
return(
<CourseList courses={this.state.courses}/>
)
}
}
我的 CourseList.jsx :
const courseList = (props) => (
<Grid>
<Row>
{
props.courses.map((course, i)=>{
return (
<Col key ={i} lg={2} sm={8} xs={12} md={6}>
<div className="course-block">
<p>{course.name}</p>
<p>AUTHOR NAME WILL BE HERE </p>
</div>
</Col>)
})
}
</Row>
</Grid>
);
export default courseList;
此代码有效,但我得到这样的作者的“承诺”。 {id: 7, name: "HTML", previewBase64: "", authors: Promise}
【问题讨论】:
-
尝试等待:
authors: await axios.get('http...... -
作者对象里面有什么?
-
在您的作者致电尝试
.subscribe之后,而不是.then
标签: javascript reactjs rest axios