在React Native中如何使用带有map()的promise

时间:2019-02-20 14:06:51

标签: typescript react-native promise jsx

我是React Native的新手,正在学习它。 我想将Promise与map()一起使用,这对我来说不是很干净,并且出现了错误:

  

“ TypeError:类型错误:undefined不是对象(正在评估   '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>
    );
  }
}

在ExploreData中

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;
  }
}

如果有人可以帮助我,那就太好了。谢谢

2 个答案:

答案 0 :(得分:1)

正如其他人指出的,this.lessons应该是this.state.lessons

答案 1 :(得分:1)

您的代码中有几种错别字:

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>
    );

  }
}