如何使用map()的promise来反应native

问题描述 投票:0回答:2

我是React Native的新手,我正在学习它。我想用map()使用Promise,对我来说不是很干净,我有一个错误:

“TypeError:Type Error:undefined不是对象(评估'this.lessons.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>
    );
  }
}

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

如果有人可以帮助我,这将是非常好的。谢谢

typescript react-native promise jsx
2个回答
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>
    );

  }
}

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.