Json 信息到 div 组件反应

Json information into a div component react

我刚开始学习 React,出于某种原因,我无法掌握如何将 json 数据放入代码的特定部分。我用另一种方法做了,但看起来很乱,所以我想把它整理成一个 json 文件。

GameVers.json
[
    { "value": "Red-blue", "id": "1" },
    { "value": "Yellow", "id": "2" },
    { "value": "gold-silver", "id": "3" },
]
    render() {
    const filteredPokemon = this.state.pokedex.filter(pokemon => {
        return pokemon.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
    })
    const gmeVs = require("./GameVers");

    return (
        <div>
            <h1>Pokemon Type Strength</h1>
            <p>Select your game and pokemon to see what types they can beat</p>
            <SearchBox searchChange={this.onSearchChange}/>
            <div style={{margin: '16px' , position: 'relative'}}>
                <FilterVers 
                    width={200}
                    name='game_id'
                    items={[ 
                        { "value": "Red-blue", "id": "1" },
                        { "value": "Yellow", "id": "2" },
                        { "value": "gold-silver", "id": "3" },
                        { "value": "crystal", "id": "4" },
                    ]}
                />
            </div>
            <PanelList pokedex={filteredPokemon}/>
        </div>
        );
}

我想要的是将 json 或 js (GameVers.json) 文件放入我的过滤器组件的

此列表较长,我将其缩短以供查看。而是将这个长列表放在另一个文件中,然后放在我的代码中间。我已经为 .map() 尝试了几种方法,但它永远不会正确。

谢谢!

您可以将数组移动到某个文件,例如constants.jsdata.js 并存储在那里:

export const GameVers = [
  { "value": "Red-blue", "id": "1" },
  { "value": "Yellow", "id": "2" },
  { "value": "gold-silver", "id": "3" },
  { "value": "crystal", "id": "4" },
];

之后,您只需导入此文件即可import { GameVers } from "./data"; 并将您的数据作为道具 items={GameVers} 传递给您的 FilterVers 组件。

我想首先不要将其制作成 *.json 文件,而是将其制作成普通的 *.js 文件,以便您可以导入它。

GameVers.js

const gameVers = [
  { "value": "Red-blue", "id": "1" },
  { "value": "Yellow", "id": "2" },
  { "value": "gold-silver", "id": "3" },
  ....
];

export default gameVers;

您应该能够正常从文件中导入 JSON 数组。

import gameVers from './GameVers';

现在您可以像使用任何其他 JS 一样使用它 array/object。

<FilterVers 
  width={200}
  name='game_id'
  items={gameVers} // <-- pass array as prop
/>