我想从正在使用的API中列出数据。但是我遇到了错误。

    // Here I'm getting the data.
    componentWillMount() {
    tokenner()
      .then(responseJson => {
        const token = "Bearer " + responseJson.result.token;
        this.setState({ token });
        fetch(
          "myapiurl//notimportant",
          {
            method: "GET",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
              Authorization: token
            }
          }
        )
          .then(response => response.json())
          .then(responseData => {
            this.setState({
              isLoading: false,
              dataSource: responseData.result
            });
          });
      })
      .catch(error => console.warn(error));
  }


然后,我使用以下代码列出我得到的数据:

render() {
if (this.state.isLoading) {
  return (
    <View style={styles.container}>
      <ActivityIndicator />
    </View>
  );
} else {
  console.warn(this.state.dataSource) // I got the data. Everything ok.
  this.state.dataSource.map((val, key) => {
    return ( // There was no data returned error.
      <View key={key} style={styles.item}>
      <Text>{val.id}</Text>
      <Text>{val.name}</Text>
      <Text>{val.surname}</Text>
      <Text>{"Sıra" + key}</Text>
      </View>
    );
  });
}


}
}

错误:
The Error

当我不使用循环而打印结果时,程序不会产生错误。
我该怎么办?

最佳答案

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

this.state.dataSource.map((val, key) => {
    return (
      <View key={key} style={styles.item}>
        <Text>{val.id}</Text>
        <Text>{val.name}</Text>
        <Text>{val.surname}</Text>
        <Text>{"Sıra" + key}</Text>
      </View>
    );
  });


^这实际上是一个元素数组。你必须在渲染中返回这个

render(){
 ......
 return this.state.dataSource.map((val, key) => {
    return (
      <View key={key} style={styles.item}>
        <Text>{val.id}</Text>
        <Text>{val.name}</Text>
        <Text>{val.surname}</Text>
        <Text>{"Sıra" + key}</Text>
      </View>
    );
  });
}

关于javascript - 如何在React Native中使用循环列出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52129110/

10-17 02:53