解析json react native

时间:2018-07-09 14:41:33

标签: javascript json reactjs react-native

我正在使用加密API在我的应用程序中加载数据。在我的示例中如何渲染价格?

我正在尝试 {item.quotes.price} ,但是没有任何解决方案?

我的源代码是:

export default class FetchExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isLoading: true };
  }

  componentDidMount() {
    return fetch("https://api.coinmarketcap.com/v2/ticker/?start=1&limit=10&sort=id&structure=array")
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            isLoading: false,
            dataSource: responseJson.data
          },
          function() {

          }
        );
      });
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, padding: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={{ flex: 1, paddingTop: 20 }}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({ item }) => (
            <Text>
              {item.name}, {item.symbol}
            </Text>
          )}
          keyExtractor={(item, index) => index}
        />
      </View>
    );
  }
}

有解决方案吗?

向所有人寻求帮助!

1 个答案:

答案 0 :(得分:2)

从请求中获得的数据在item.quotes.UDS.price下是item.quotes.price,而不是dataSource

还要确保在您的状态下初始化一个空的class FetchExample extends React.Component { constructor(props) { super(props); this.state = { isLoading: true, dataSource: [] }; } componentDidMount() { return fetch("https://api.coinmarketcap.com/v2/ticker/?start=1&limit=10&sort=id&structure=array") .then(response => response.json()) .then(responseJson => { this.setState({ isLoading: false, dataSource: responseJson.data }); }); } render() { if (this.state.isLoading) { return ( <View style={{ flex: 1, padding: 20 }}> <ActivityIndicator /> </View> ); } return ( <View style={{ flex: 1, paddingTop: 20 }}> <FlatList data={this.state.dataSource} renderItem={({ item }) => ( <Text> {item.name}, {item.symbol}, {item.quotes.USD.price} </Text> )} keyExtractor={(item, index) => index} /> </View> ); } } 数组:

  messages: string[] = ['a', 'b', 'c'];
  const source = from(messages)