简体   繁体   English

如何从本地文件返回React中的JSON数组,并使其映射到我的所有项目?

[英]How do I return a JSON array in React from a local file and have it map through all of my items?

Notes: using React for this. 注意:为此使用React。

Basically, I'm just trying to make a list of anchor elements from a list of links I have stored locally in a json file. 基本上,我只是想从我本地存储在json文件中的链接列表中创建锚元素列表。 I can confirm that the file is successfully seeing the "endpoints" data through console logs. 我可以通过控制台日志确认文件已成功看到“端点”数据。 However, the page just renders a white page and it doesn't look like the state is getting set correctly with the imported array. 但是,该页面仅呈现白色页面,并且看起来好像不是使用导入的数组正确设置了状态。 So, this is what my file looks like right now (Any help would be greatly appreciated!): 因此,这就是我的文件现在的样子(任何帮助将不胜感激!):

 import React from 'react'; import endpoints from './endpoints.json'; class Link extends React.Component{ constructor(props){ super(props); this.state = { error: null, isLoaded: false, myData: [] }; } componentDidMount() { let myData = endpoints.map((data, key) => { console.log(endpoints); console.log(endpoints[0].key); return( <a className="aLink" href={endpoints.link} key={endpoints.key} >{endpoints.name}</a> ) }) this.setState({myData: myData}); console.log(this.state.myData); } render() { const { error, isLoaded } = this.state; if (error) { return <div className="errorM">Error: {error.message}</div>; } else { return( <div> {this.state.myData} </div> ) } } } export default Link; 

You seem to be trying to render from the initial response (endpoints) rather than the map value (data). 您似乎正在尝试从初始响应(端点)而不是地图值(数据)进行渲染。 Change 更改

href={endpoints.link} key={endpoints.key} >{endpoints.name}

to

href={data.link} key={data.key} >{data.name}

Well, this was one of those classic, ask a question and then immediately figure out the answer. 好吧,这是经典之作之一,问一个问题,然后立即找出答案。 Basically, where I'm mapping each item, I set an argument called "data". 基本上,我在映射每个项目的地方都设置了一个称为“数据”的参数。 Instead of calling "endpoints.xxx" it should be "data.xxx" for everything. 而不是调用“ endpoints.xxx”,所有内容都应为“ data.xxx”。 Then, everything renders fine. 然后,一切呈现正常。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM