【问题标题】:Can't import JSON in react无法在反应中导入 JSON
【发布时间】:2019-11-13 21:59:31
【问题描述】:

我确定这是一个愚蠢的问题,但我似乎找不到解决方法。

我有一个反应应用程序,我正在尝试导入一个 JSON 文件。这里是:

{ 
   "words":{ 
      "ita":[ 
         "ora",
         "via",
         "dio",
         "sud",
         "don",
         "zia"
      ]
   }
}

这是反应代码:

import React, { Component} from 'react'

import words from 'Assets/Words.json'

console.log(words)
console.log(words.ita)

export default class WordsGen extends Component {
  ...

两个console.log分别打印:

{words: {…}}
  words:
    ita: (6) ["ora", "via", "dio", "sud", "don", "zia"]
  __proto__: Object
__proto__: Object

undefined

我正在使用 json 文件在应用程序中添加更多语言,但我不明白为什么当我只打印 words 时,我可以在里面看到属性 ita,而当我尝试打印 @987654328 时@ 或 words["ita"] 我不确定。

我错过了什么?

【问题讨论】:

    标签: javascript json reactjs


    【解决方案1】:

    应该是:

    words.words.ita
    

    您正在导入为“单词”,然后该对象有一个单词对象。更改导入名称可能更清楚:

    import MyJson from 'my.json';
    
    console.log(MyJson.words.ita)
    

    【讨论】:

    • 理论上你也可以使用对象扩展来导入import { words } from 'my.json'。然后就可以按照作者的意图使用了(words.ita)。
    【解决方案2】:

    因为您导入的对象 words 包含整个 json。当你写

    import words from 'Assets/Words.json';
    

    会变成

    words = { 
       words:{ 
          ita:[ 
             "ora",
             "via",
             "dio",
             "sud",
             "don",
             "zia"
          ]
       }
    }
    

    这就是为什么你的对象words 没有真正的属性ita。这就是为什么它会返回undefined

    你需要写words.words.ita。为了更好的代码风格:

    /// words.json
    { 
       "ita":[ 
           "ora",
           "via",
           "dio",
           "sud",
           "don",
           "zia"
          ]
    }
    
    import words from 'Assets/Words.json';
    words.ita // then your code
    
    /// or even better with new es6 destructing
    import {ita = []} from 'Assets/Words.json';
    
    ita // do anything that you want
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2021-11-22
      • 2020-11-06
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多