【问题标题】:Add local json file to fetch objects in React添加本地 json 文件以在 React 中获取对象
【发布时间】:2018-11-22 05:49:03
【问题描述】:

您好,我想知道从以下格式的本地文件中获取 JSON 对象的最佳方法是从这些 JSON 列表中呈现键值空气列表。我试图导入如下所述的文件,但它是徒劳的。我想知道如何从本地 json 文件中获取这些键值对以使用 jsx 显示。任何线索将不胜感激。例如,如果我想显示“John 在 12.20 pm 接到来自美国的电话”。 John 在 Calls 下作为 name ID 传递,在 States 下作为 location 传递。

{"Calls":[there are list of key values pairs
],
"States":[there are a list of key value pairs],
"time:[list of key value pairs]"} 

反应代码:

import jsonData from "./example.json";

const loadData = () => JSON.parse(JSON.stringify(jsonData));

constructor() {
    super();
    this.state = {
      userList: []
    };
   }

   componentWillMount() {
    axios.get('./example.json') // JSON File Path
      .then( response => {
        this.setState({
        userList: response.data
      });
    })
    .catch(function (error) {
      console.log(error);
    });
   }

   render() {
  const usersList = this.state.userList;
  let usersListBlock = '';

  if(usersList.length > 0) {
    usersListBlock = usersList.map( obj => {
      return (
        <Usercard key={obj.id} id={obj.id} id={obj.number} name={obj.name} />
            )
    })
   }

   return(
    <div className="row container">
        {usersListBlock}
    </div>
   )
}

【问题讨论】:

标签: javascript json reactjs


【解决方案1】:

您可以直接通过导入使用json文件,然后您可以直接使用json对象或将其设置为状态。 像你已经做的那样导入 Json 文件

import jsonData from "./example.json";

然后在设置状态或者直接使用

componentWillMount() {
    this.setState({userList:jsonData })

   }

【讨论】:

  • 是的,我试过react DOM不识别这个路径,找不到文件内容。
【解决方案2】:

我遇到了同样的问题,尝试将 JSON 文件保存在公用文件夹中,然后用 axios.get('example.json') 调用它,它对我来说很好。

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2019-06-06
    • 2015-06-09
    • 2021-03-09
    • 2021-12-03
    相关资源
    最近更新 更多