【发布时间】:2016-07-12 07:15:11
【问题描述】:
我正在访问从我的模拟 API 返回的承诺。 React 组件看起来像您在下面看到的那样
import React from 'react';
import StudentListStatistics from './StudentListStatistics';
import StudentStatisticsApi from '../../api/mockStudentApi';
class AboutPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
studentsStatistics: []
};
}
componentDidMount() {
StudentStatisticsApi.getAllStudentsStatistics().then(
studentsStatistics => {
this.setState({
studentsStatistics: studentsStatistics
});
debugger;
}
);
console.log(this.state.studentsStatistics);
}
render() {
return (
<div>
<h2>Student Body Statistics</h2>
<StudentListStatistics studentsStatistics={this.state.studentsStatistics}/>
</div>
);
}
模拟 API 如下所示
class StudentApi {
static getAllStudentsStatistics() {
return new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve(Object.assign([], studentsStatistics));
}, 1000);
});
}
我不确定为什么 this.state.studentsStatistics 总是一个空数组。如果我单步执行代码,则在 then 回调中从我的模拟 API 正确返回了 studentsStatistics 数组。
有人可以指出我可能缺少什么。
【问题讨论】:
-
你的意思是
console.log()总是显示一个空数组吗?还是什么也没有渲染? -
console.log() 显示 [] - 渲染很好 -
组件按预期显示警告,因为正在将空数组传递给预期的 StudentListStatistics 组件。我在 StudentListStatistics 组件中设置了所需的 PropType 验证,因此我收到以下警告“警告:失败的 propType:所需的道具 studentBodyStatistics未在StudentStatisticsRow中指定。检查StudentListStatistics的渲染方法。” -
console.log显示一个空数组是有道理的,但我认为(最终)您的StudentListStatistics会呈现模拟数据(最初它会收到一个空数组,因为这是组件的初始状态)。 -
但是一旦 ComponentDidMount 被触发,console.log 应该会显示正在返回的数据。我同意最初它是一个空数组,但即使在触发 componentDidMount 之后,也会返回 []
-
如果您使用箭头函数 (
=>),请不要使用self = this,因为它们具有词法this范围。不要将延迟承诺和包含逻辑混为一谈 - 而是构建一个delay原语并使用它。您不需要在文字中重复对象属性,{ studentsStatistics:studentsStatistics }只是{studentsStatistics}。不要使用debugger,在开发者工具中使用断点(在你的代码中忘记调试器会去优化你的代码)