gpt4 book ai didi

javascript - 在 React Native Picker 中仅渲染唯一标签

转载 作者:行者123 更新时间:2023-11-29 16:36:19 30 4
gpt4 key购买 nike

我有一个 JSON,也可以通过 http://myjson.com/kfd04 访问

{
"response": [
{
"id": "1",
"customer": "Star Wars",
"project": "1977"
},
{
"id": "2",
"customer": "Star Wars",
"project": "1985"
},
{
"id": "3",
"customer": "The Matrix",
"project": "1999"
},
{
"id": "4",
"customer": "Inception",
"project": "2010"
},
{
"id": "5",
"customer": "Interstellar",
"project": "2014"
}
]
}

我只想呈现唯一的客户,这是我到目前为止的代码。它显示所有客户。 responseData 包含“response”对象数组。

<Picker
mode="dialog"
selectedValue={this.state.customerName}
onValueChange={(itemValue, itemIndex) => {
this.setState({ customerName: itemValue });
}
}
>
{
this.state.responseData.map((item) => (
<Picker.Item label={item.customer} value={item.customer} key={item.customer} />))
}
</Picker>

最佳答案

您需要减少数组以过滤掉唯一值,为此您可以使用reduce方法

const data = {
"response": [
{
"id": "1",
"customer": "Star Wars",
"project": "1977"
},
{
"id": "2",
"customer": "Star Wars",
"project": "1985"
},
{
"id": "3",
"customer": "The Matrix",
"project": "1999"
},
{
"id": "4",
"customer": "Inception",
"project": "2010"
},
{
"id": "5",
"customer": "Interstellar",
"project": "2014"
}
]
}
const arr = data.response.reduce((acc, item) => {
if(!acc.includes(item.customer)) {
acc.push(item.customer);
}
return acc;
}, [])

console.log(arr);

然后你可以像这样渲染它

render() {

const reducedArr = this.getUniqueValues();
return (
<Picker
mode="dialog"
selectedValue={this.state.customerName}
onValueChange={(itemValue, itemIndex) => {
this.setState({ customerName: itemValue });
}
}
>
{
reducedArr.map((customer) => (
<Picker.Item label={customer} value={customer} key={customer} />))
}
</Picker>
)
}

const data = {
"response": [
{
"id": "1",
"customer": "Star Wars",
"project": "1977"
},
{
"id": "2",
"customer": "Star Wars",
"project": "1985"
},
{
"id": "3",
"customer": "The Matrix",
"project": "1999"
},
{
"id": "4",
"customer": "Inception",
"project": "2010"
},
{
"id": "5",
"customer": "Interstellar",
"project": "2014"
}
]
}
const arr = data.response.reduce((acc, item) => {
if(!acc[item.customer]) {
acc[item.customer] = 1;
}
return acc;
}, {})

console.log(arr);

然后你可以像这样渲染它

render() {

const reducedObject = this.getUniqueValues();
return (
<Picker
mode="dialog"
selectedValue={this.state.customerName}
onValueChange={(itemValue, itemIndex) => {
this.setState({ customerName: itemValue });
}
}
>
{
Object.keys(reducedObject).map((customer) => (
<Picker.Item label={customer} value={customer} key={customer} />))
}
</Picker>
)
}

或者要过滤掉唯一值,您还可以使用 Javascript Set

关于javascript - 在 React Native Picker 中仅渲染唯一标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153484/

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