0

私はネイティブに反応する初心者で、JSON データを取得するためのシンプルなアプリを作成したいと考えています。

これが私のjsonファイルです。

[
  {
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
  },
  {
    "fruit": "Orange",
    "size": "big",
    "color": "Orange"
  }
]

これが私の反応するネイティブコードです

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { data: '' };
    }
    componentDidMount = () => {
        fetch('https://othersite.my.json', {
            method: 'GET'
        })
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                this.setState({
                    data: responseJson
                })
            })
            .catch((error) => {
                console.error(error);
            });
    }
    render() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.data}
                    //for debug {this.state.data.fruit}
                </Text>
            </View>
        );
    }
}

しかし、うまくいきません。

4

2 に答える 2

0

あなたのフェッチはそこによく見えます。APIからデータを取得して状態を設定できることを考慮してください。map() 関数を使用してデータを表示できます

render(){
  return (
    <View style={styles.container}>
       {this.state.data.map((item) => {
         console.log(item.fruit)
         console.log(item.size)
         console.log(item.color)
       })
    </View>
  );
}
于 2021-05-28T02:59:44.633 に答える