【问题标题】:How to create a list of option tags from a JSON file in ReactJS如何在 ReactJS 中从 JSON 文件创建选项标签列表
【发布时间】:2018-06-02 22:19:43
【问题描述】:

我对 ReactJS 很陌生,我正在玩表单。 具体来说,我正在尝试根据(本地)JSON 文件中的条目构建<option> 标签列表。

通过调试器,我可以看到值被正确读取和解析。然而,呈现的页面中没有出现任何内容,我不太清楚为什么。

这是我写的组件:

import React, { Component } from 'react';

const countries = require('../Data/countries.json')

class Countries extends Component {
  constructor(props) {
    super(props);
    this.state = {
      countries: countries,
    }
  };

  render() {
    return (
      <div className="Countries">
        <select name={this.props.name}>
        {
          Object.entries(this.state.countries).forEach((entry, _) => {
            let key = entry[0]
            let value = entry[1]
            return <option value={key}>{value}</option>
          })
        }
        </select>
      </div>
    );
  }
}

export default Countries;

JSON 文件来自https://raw.githubusercontent.com/umpirsky/country-list/master/data/en_GB/country.json。 因此,条目类似于"CC": "Country name"

在主App.js中,我像这样实例化Countries

<Countries name="country" />

我看不到任何明显的遗漏。这是什么?

【问题讨论】:

    标签: javascript forms reactjs


    【解决方案1】:

    Array#forEach 没有返回值,回调中的return 什么也不做

    改用Array#map()

     <select name={this.props.name}>
        {
          Object.entries(this.state.countries).map((entry, _) => {
            let key = entry[0]
            let value = entry[1]
            return <option value={key}>{value}</option>
          })
        }
     </select>
    

    或者使用 Object.keys()

     <select name={this.props.name}>
        {
          Object.keys(this.state.countries).map(key => {           
            return <option value={key}>{this.state.countries[key]}</option>
          })
        }
     </select>
    

    【讨论】:

    • 谢谢!谷歌搜索一下forEachmap 之间的区别我遇到了these two statements,这可能对遇到类似问题的人有用:forEach() — 为每个数组元素执行一次提供的函数。 map() — 创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。
    • MDN 文档是很好的资源。告诉你返回什么developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多