[英]Getting .filter to work with .map from JSON object in React.Js
I am trying to get my second dropdown to populate based on what is selected in the first dropdown. 我试图根据第二个下拉列表中的第一个下拉列表进行填充。
The first dropdown lists the tableName
s from the JSON below. 第一个下拉列表从下面的JSON列出
tableName
。 I want the second dropdown to be columns
for the selected tableName
. 我希望第二个下拉列表是所选
tableName
columns
。
For now though I just wanted to see a list of the columns
where tableName == 'customer'
. 现在,尽管我只想查看
tableName == 'customer'
的columns
的列表。
I am trying to use the .filter
method along with the .map
method to accomplish this, but the second dropdown is empty. 我正在尝试使用
.filter
方法和.map
方法来完成此操作,但是第二个下拉列表为空。 Here is the current code I have: 这是我当前的代码:
import React from 'react';
import axios from 'axios';
class Search extends React.Component {
constructor(props) {
super(props)
this.state = {
Params: [],
ColumnParams: []
}
}
componentWillMount() {
axios.get('http://localhost:3010/api/schema')
.then(response => {
this.setState({Params: response.data})
})
}
render() {
return (
<div className="Search">
<select>{this.state.Params.map((param, i) =>
<option key={i}>{param.tableName}</option>)}
</select>
<select>{this.state.Params.filter(tn => tn === "customer").map(param =>
<option>{param}</option>)}
And here is the JSON: 这是JSON:
[
{
"tableName": "customer",
"columns": [
"customerid",
"title",
"prefix",
"firstname",
"lastname",
"suffix",
"phone",
"email"
]
},
{
"tableName": "product",
"columns": [
"productid",
"name",
"color",
"price",
"productadjective",
"productmaterial"
]
}
]
Params
in your state is an array of objects but in your filter you are trying to compare it with a string. 状态下的
Params
是一个对象数组,但是在过滤器中,您试图将其与字符串进行比较。
Try 尝试
.filter(({tableName}) => tableName === 'customer')
.map(({columns}) =>
columns.map((col) =>
<option>{col}</option>))}
instead. 代替。
Given the JSON: 鉴于JSON:
[
{
"tableName": "customer",
"columns": [
"customerid",
"title",
"prefix",
"firstname",
"lastname",
"suffix",
"phone",
"email"
]
},
{
"tableName": "product",
"columns": [
"productid",
"name",
"color",
"price",
"productadjective",
"productmaterial"
]
}
]
Your comparison in the filter method is wrong, you can change to use destructuring assignment : 您在filter方法中的比较是错误的,您可以更改为使用解构分配 :
import React from 'react';
import axios from 'axios';
class Search extends React.Component {
constructor(props) {
super(props)
this.state = {
params: [],
columnParams: []
}
}
componentWillMount() {
axios
.get('http://localhost:3010/api/schema')
.then(response => this.setState({params: response.data}))
}
render() {
const tableNames = this.state.params
.map(({tableName}, i) => <option key={i}>{tableName}</option>);
const params = this.state.params
.filter({tableName} => tableName === "customer")
.map({columns} => <option>{columns}</option>);
return (
<div className="Search">
<select>{tableNames}</select>
<select>{params}</select>
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.