【问题标题】:How to render the JSON file in reactJS如何在 reactJS 中渲染 JSON 文件
【发布时间】:2021-08-13 01:55:50
【问题描述】:

我有这样的 JSON 文件

[{
  "amenity": ["bar", "restaurant", "college", "library", "school", "university", "atm", "bank", "clinic", "hospital", "pharmacy", "nursing_home", "cinema", "embassy", "fire_station", "police", "post_office", "toilets", ""],
  "Buildings": ["yes", "apartments", "bungalow", "hotel", "house", "residential", "commercial", "supermarket", "school", "religious", "hospital", "government", "college"],
  "highway": ["motorway", "trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "pedestrian", "footway", "path", "bus_stop"]
}]

我需要在 react 组件中显示这个 JSON 文件。我需要在第一个中显示两个选择选项我需要在第二个中选择 3 个键中的任何一个,例如设施、建筑物、高速公路我需要在第二个对象中显示数组的相应值

【问题讨论】:

  • 你试过什么?包含相关的 React 组件类代码。
  • 我尝试过使用 React 函数式组件

标签: javascript html json reactjs drop-down-menu


【解决方案1】:

你可以在 React 中轻松做到这一点。您只需要通过第一个对象的键来呈现第一个列表。至于第二个下拉,使用当前选择的类别。

const { useEffect, useState } = React;

const fetchData = () => Promise.resolve([{
  "amenity": ["bar", "restaurant", "college", "library", "school", "university", "atm", "bank", "clinic", "hospital", "pharmacy", "nursing_home", "cinema", "embassy", "fire_station", "police", "post_office", "toilets", ""],
  "building": ["yes", "apartments", "bungalow", "hotel", "house", "residential", "commercial", "supermarket", "school", "religious", "hospital", "government", "college"],
  "highway": ["motorway", "trunk", "primary", "secondary", "tertiary", "unclassified", "residential", "pedestrian", "footway", "path", "bus_stop"]
}]);


const App = (props) => {
  const [data, setData] = useState([]);
  const [selected, setSelected] = useState(null);

  const changeSelection = (e) => setSelected(e.target.value);

  useEffect(() => fetchData().then(json => setData(json)), []);

  const [categories = {}] = data, types = categories[selected] || [];
  
  return (
    <div>
      <select onChange={changeSelection}>{
        ['', ...Object.keys(categories)].map(cat => (
          <option value={cat} selected={selected === cat}>{cat}</option>
        ))
      }</select>
      <select>{types.map(type => (<option value={type}>{type}</option>))}</select>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多