【发布时间】:2019-07-14 06:09:09
【问题描述】:
我是 React Native 的新手,我正在学习它。 我想将 Promise 与 map() 一起使用,这对我来说不是很干净,而且我遇到了一个错误:
"TypeError: 类型错误: undefined is not an object (evaluate 'this.lessons.map')"
在探索屏幕中
interface IProps {
navigation: NavigationScreenProp<any, any>;
}
interface IState {
lessons: ILesson | [];
}
export class ExploreScreen extends Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {lessons: []}
}
public async componentDidMount() {
this.setState({lesson: await ExploreData.getData()});
}
public render() {
let block
if(this.state.lessons === null) {
block = <View><Text>Loader</Text></View>;
} else {
block = (
<ScrollView>
{this.lessons.map((lesson: ILesson) => (
<LessonListItem
key={lesson.id}
lesson={lesson}
/>))}
</ScrollView>
);
}
return (
<View>
{block}
</View>
);
}
}
在探索数据中
export class ExploreData extends CoreData {
public static async getData(id: string): Promise<ILesson[]>{
await ExploreData.wait();
const data = [];
for (let i = 0; i < 25; i++) {
data.push(CoreData.getLesson());
}
return data;
}
private static wait(): Promise<{}> {
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve(), 2000);
});
return promise;
}
}
如果有人可以帮助我,那就太好了。谢谢
【问题讨论】:
-
this.lessons不存在,应该是this.state.lessons -
错字
this.lessons.map->this.state.lessons.map? -
感谢您的回答,错误消失了,但什么也没有出现,没有教训:/
-
第二个错误:在componentDidMount中你设置了
this.setState({lesson: ...},应该是this.setState({lessons: ...}
标签: typescript react-native promise jsx