【问题标题】:Trying to display JSON Data, but receiving JSON Parse Error尝试显示 JSON 数据,但收到 JSON 解析错误
【发布时间】:2020-02-18 19:22:33
【问题描述】:

我正在尝试在我的屏幕上显示 JSON 数据,确切地说是整数 4。

但是,我收到 JSON 解析错误。

我已经发布并且工作正常,因为 Webhooksite 说它已成功发布。此外,它“变得”很好,但数据不显示。请帮忙!

// JSON Data

{
    "cheetosamount": 4,
    "cookiesvalue": 2
}
export default class ChooseDeliveries extends Component {

  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    }
  }
  componentDidMount(){
    this.handleGetRequest();
  }

  handleGetRequest() {
    fetch ('https://webhook.site/e61dd236-92d5-4b3b-882b-a50d6add6cd3',{
      method: 'GET',
    })
    .then(response => response.json())
    .then(responseJson => {
      this.setState({
        dataSource: JSON.parse(responseJson),
        isLoading: false,
      })
    })
    .catch(error => {
      console.error(error);
    });
  };


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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

【问题讨论】:

    标签: json reactjs react-native


    【解决方案1】:

    我相信这是因为你得到的“JSON”已经是一个对象,你不需要解析它。

    这里提供了更深入的解释SyntaxError: Unexpected token o in JSON at position 1

    在您的 chrome 控制台中尝试以下操作

    let c ={
        "cheetosamount": 4,
        "cookiesvalue": 2
    }
    
    c.cheetosAmount
    

    所以基本上你所要做的就是

     this.setState({
            dataSource: responseJson,
            isLoading: false,
          })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多