提问者:小点点

在React Native中连接REST API


我正在尝试学习如何在React Native中连接API。 我正在使用一个示例API:https://reactnative.dev/movies.json

这是我的代码:

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dataSource: [],
    };
  }
  componentDidMount() {
    return fetch("https://reactnative.dev/movies.json")
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          loading: false,
          dataSource: responseJson.movies,
        });
      })
      .catch((error) => console.log(error)); //to catch the errors if any
  }
  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator size="large" color="#0c9" />
        </View>
      );
    } else {
      let products = this.state.dataSource.map((val, key) => {
        return (
          <View key={key} style={styles.item}>
            <Text>{val}</Text>
          </View>
        );
      });
      return (
        <View style={styles.container}>
          <Text>{products.title}</Text>
        </View>
      );
    }
  }
}

问题发生在我的“products”变量上。 在调试模式下,我能够从API中看到正确的对。 但是,products数组是用对象而不是字符串填充的,字符串的结构如下:object{$$TypeOf:Symbol(React.Element),type:“RCTView”,key:“0”,…}

我的代码返回以下错误:this.state.datasource.map is not a function


共1个答案

匿名用户

尝试一下,我已经使用object.values()将对象重组为数组

  componentDidMount() {
    return fetch("https://reactnative.dev/movies.json")
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          loading: false,
          dataSource: Object.values(responseJson.movies),       //changed this
        });
      })
      .catch((error) => console.log(error)); //to catch the errors if any
  }