【问题标题】:How to use promise with map() in react native如何在本机反应中使用带有 map() 的 Promise
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您的代码中有几个拼写错误:

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

    【讨论】:

      猜你喜欢
      • 2016-07-26
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 2019-06-27
      • 2021-12-29
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多