gpt4 book ai didi

javascript - 如何在 ReactJS 中从 JSON 文件创建选项标签列表

转载 作者:行者123 更新时间:2023-11-30 14:34:15 25 4
gpt4 key购买 nike

我是 ReactJS 的新手,正在研究表单。具体来说,我正在尝试构建 <option> 的列表基于(本地)JSON 文件中条目的标签。

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

这是我写的组件:

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" />

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

最佳答案

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>

关于javascript - 如何在 ReactJS 中从 JSON 文件创建选项标签列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com