代码之家  ›  专栏  ›  技术社区  ›  Pointer

解析json react native

  •  1
  • Pointer  · 技术社区  · 7 年前

    我正在使用crypto 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 回复  |  直到 7 年前
        1
  •  2
  •   Tholle    7 年前

    从请求中获取的数据具有 price 在下面 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>
        );
      }
    }
    
    推荐文章