简体   繁体   English

如何 map 从反应 state 到 select 框的字符串数组

[英]How to map an array of strings from react state to a select box

I read a json file in the first select box and set the value as state and i don't know how to read that value to another select box. I read a json file in the first select box and set the value as state and i don't know how to read that value to another select box. All I get is the whole array as one string.我得到的只是整个数组作为一个字符串。

This is the code where i set state as an object from the first select box:这是我从第一个 select 框中将 state 设置为 object 的代码:

constructor(props) {
    super(props);
    this.state = {
        selectedCourse: {}
        
    };
    this.onSelectCourse = this.onSelectCourse.bind(this);
}
onSelectCourse(e) {
    console.log(e.target);
    this.setState(
        {
            selectedCourse: {
                ...this.state.selectedCourse,
                [e.target.id]: [e.target.value]
            }
        },
        () => {
            console.log(this.state);
        }
    );
}

render() {
    const { selectedCourse } = this.state;

This is the first select box:这是第一个 select 盒子:

<select onChange={this.onSelectCourse}>{CoursesList.courses.map((item, i) =><option key={i} value={item.dates}>{item.name}</option>)}</select>

This is the select box where i want to display the data from state object array:这是 select 框,我想在其中显示来自 state object 数组的数据:

<select>{Object.entries(this.state.selectedCourse).map((item) =><option key={item}>{item}</option>)}</select>

The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] Object.entries()方法返回给定对象自己的可枚举字符串键属性 [key, value] 的数组

Meaning each item in the .map function is an array such as [key, value] .这意味着.map function 中的每个item都是一个数组,例如[key, value]

What I think you want to do is,我想你想做的是,

<select>
{Object.entries(this.state.selectedCourse)
  .map(
   ([key, value]) => (<option key={key} value={value}>{value}</option>)
  )
}
</select>

If you just want the object values and not the keys, you can use Object.values() or for inverse Object.keys() .如果您只想要 object 值而不是键,则可以使用Object.values()或反向Object.keys()


Also, in your setState you are accessing [e.target.id] but your <option> tag has no id attribute set.此外,在您的setState中,您正在访问[e.target.id]但您的<option>标签没有设置id属性。


EDIT :编辑

As pointed out by OP,正如OP所指出的,

But in my select box I still get: 2017-05-03,2018-02-01 (as one option)但在我的 select 盒子里,我仍然得到:2017-05-03,2018-02-01(作为一种选择)

I think that could be because of the item.dates in first select field ( <option key={i} value={item.dates}>{item.name}</option> ).我认为这可能是因为第一个item.dates字段中的 item.dates ( <option key={i} value={item.dates}>{item.name}</option> )。 Is the item.dates an array? item.dates是一个数组吗? I recommend you check your JSON.我建议您检查您的 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM