【问题标题】:How to get all JSON data inside the brackets using fetch?如何使用 fetch 获取括号内的所有 JSON 数据?
【发布时间】:2021-05-28 02:41:07
【问题描述】:

我是反应原生的新手,我想创建一个简单的应用程序来获取 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>
        );
    }
}

但它不起作用。

【问题讨论】:

  • 您是否设置了正确的 my.json 路径。它可能类似于 ./my.json 或 ./../my.json
  • 抱歉我的描述不清楚,这不是我主机中自己的json文件,它使用了另一个站点的HTTPS URL路径,谢谢
  • 控制台里有什么?

标签: javascript arrays json react-native


【解决方案1】:

您的 fetch 在那里看起来不错。考虑到您能够从 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>
  );
}

【讨论】:

  • 非常感谢,它工作正常 :) 。祝你有美好的一天
  • 并更改 this.state = { data: '' }; to this.state = { data: [] };
【解决方案2】:

如果 json 文件在你的 react 项目中,你可以像这样导入:

const fruits = require('path/to/json/my.json');
console.log(fruits[0].size);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 2011-04-09
    • 2020-02-01
    相关资源
    最近更新 更多