我是新手反应本地的,我正在学习。我想使用Map()使用Promise,这对我来说不是很干净,我有一个错误:
" TypeError:类型错误:未定义不是对象(评估 'this.lessers.map')"
在ExploresCreen中
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;
}
}
如果有人可以帮助我,那就太好了。谢谢
您的代码中有几个错别字:
export class ExploreScreen extends Component {
public async componentDidMount() {
// Typo here:
this.setState({lessons: await ExploreData.getData()});
}
public render() {
let block
if(this.state.lessons === null) {
block = <View><Text>Loader</Text></View>;
}else{
block=(<ScrollView>
{
// Typo here:
this.state.lessons.map((lesson: ILesson) => (
<LessonListItem
key={lesson.id}
lesson={lesson}
/>
))
}
</ScrollView>
);
}
return (
<View>
{block}
</View>
);
}
}
正如其他人指出的那样,this.lessons
应该是this.state.lessons