gpt4 book ai didi

javascript - 从 JSON react 映射菜单

转载 作者:行者123 更新时间:2023-12-01 01:14:33 26 4
gpt4 key购买 nike

我有一个滚动菜单项,每个项目的标题都与 id 一起硬编码为 const

const list = [
{ name: "category1", id: 0 },
{ name: "category2", id: 1 },
{ name: "category3", id: 2 },
{ name: "category4", id: 3 },
{ name: "category5", id: 4 },
{ name: "category6", id: 5 },
{ name: "category7", id: 6 },
{ name: "category8", id: 7 }
];

我有一个 json 文件,其中包含每个子项的类别名称:

    {
"results": [
{
"category": "category1",
"name": {
"title": "mr",
"first": "ernesto",
"last": "roman"
},
"email": "ernesto.roman@example.com",
"id": {
"name": "DNI",
"value": "73164596-W"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/73.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/73.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/73.jpg"
}
},
{
"category": "category2",
"name": {
"title": "mr",
"first": "adalbert",
"last": "bausch"
},
"email": "adalbert.bausch@example.com",
"id": {
"name": "",
"value": null
} etc....

我想显示这些类别"category": "category1",作为我的菜单的标题,我现在需要启动无状态并从 JSON 添加它们,从 JSON 中获取部分JSON 是在 componentDidMount 中本地完成的,但我不确定如何将它们映射为显示为菜单名称以使菜单动态,我基本上想要相同的输出,但不是硬编码的 json。这是一个沙箱片段,非常感谢您的帮助。

https://codesandbox.io/s/2prw4j729p?fontsize=14&moduleview=1

最佳答案

只需使用结果中的 map 函数将 JSON 输出转换为 list 等对象,然后将其设置为状态上的 MenuItems ,这是您传递给 render() 函数的内容。就这样。

import React, { Component } from "react";
import ScrollMenu from "react-horizontal-scrolling-menu";
import "./menu.css";

// One item component
// selected prop will be passed
const MenuItem = ({ text, selected }) => {
return (
<div>
<div className="menu-item">{text}</div>
</div>
);
};

// All items component
// Important! add unique key
export const Menu = list =>
list.map(el => {
const { name, id } = el;
return <MenuItem text={name} key={id} />;
});

const Arrow = ({ text, className }) => {
return <div className={className}>{text}</div>;
};

export class Menucat extends Component {
state = {
selected: "0",
MenuItems: []
};

componentDidMount() {
fetch("menu.json")
.then(res => res.json())
.then(result => {
const items = result.results.map((el, idx) => {
return { name: el.category, id: idx };
});
this.setState({
isLoaded: true,
MenuItems: items
});
});
}

render() {
const { selected, MenuItems } = this.state;
// Create menu from items
const menu = Menu(MenuItems, selected);

return (
<div className="App">
<ScrollMenu
data={menu}
selected={selected}
onSelect={this.onSelect}
alignCenter={true}
tabindex="0"
/>
</div>
);
}
}

export default Menucat;

干杯!

关于javascript - 从 JSON react 映射菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889986/

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