【发布时间】:2018-04-03 01:34:50
【问题描述】:
我目前是一名初学者,正在研究 React/Redux 的一个项目。我正在尝试从 API 文件调用 JSON,将其保存为对象数组,然后将其传递到另一个文件以开始从中提取数据。我最近被困在一个地方
下面是我的课程,它正在访问 JSON 数据并将其拉出以放入数组中。我在类之外初始化了数组,但它没有被写入。我不太确定如何将我需要的数组“扔”出课堂。
numberendpoint.json(对象数组)
[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
在 index.js 中
let productJSON = [] //initialize productJSON array here
class Hue extends React.Component {
constructor() {
super();
this.state = {
elements: [],
productJSON: []
};
}
componentWillMount() {
fetch('numberendpoint.json')
.then(results => {
return results.json();
}).then(data => {
let colorArray = [] //initialize array to receive json data
for (let i =0; i < data.length; i++) {
colorArray.push(data[i])
}
productJSON = JSON.stringify(productArray) //here is where I try to assign the productJSON array
let elements = data.map((rainbow) => {
return (
<div key={rainbow.results}>
<p>{raindow.color}</p>
<p>{rainbow.value}</p>
</div>
)
})
this.setState({elements: elements});
console.log("state", this.state.elements[0]);
})
}
render() {
return (
<div>
<div className="container2">
{this.state.elements}
</div>
</div>
)}
}
如何访问 JSONproduct 数组?或者,我如何将它从这个类中“弹出”出来以便我可以使用它?
更新:使用了 Rahamin 建议的解决方案。现在我在下面有这段代码,全部包含在“Hue”类中。但我仍然遇到错误。
import React from 'react'
const TIMEOUT = 100
let productJSON;
class Hue extends React.Component {
constructor() {
super();
this.state = {
products: [],
};
this.getColors = this.getColors.bind(this)
}
componentDidMount() {
fetch('http://tech.work.co/shopping-cart/products.json')
.then(results => {
return results.json();
}).then(data => {
let colorArray = []
for (let i =0; i < data.length; i++) {
colorArray.push(data[i])
}
console.log("jsonproduct=" + JSON.stringify(productArray))
productJSON = JSON.stringify(productArray)
this.setState({productJSON: productJSON});
});
}
render() {
return (
<div>
<div className="container2">
{this.state.productJSON}
</div>
</div>
)
}
}
export default {
getProducts: (cb, timeout) => setTimeout(() => cb(({ productJSON: value})), timeout || TIMEOUT), // here is where I am getting an error -- "value" is undefined. I'm not sure I was meant to put "value" there or something else...very new to React so its conventions are still foreign to me.
buyProducts: (payload, cb, timeout) => setTimeout(() => cb(), timeout || TIMEOUT)
}
【问题讨论】:
-
需要全局访问的数据应该存储在redux状态。如果您只需要子组件中的数据,请将其作为道具传递。我强烈建议您在开始之前查看一些 redux react 教程
-
您能解释一下为什么您认为您所尝试的方法不起作用吗?我看不到任何尝试在类之外使用 productJSON 变量的代码
-
fetch应在componentDidMount调用 -
谢谢@klugjo,我学习 React-Redux 的时间很短,所以我还在学习状态。
-
@MartinBooth 你是对的,我认为我实际上并没有试图在方法之外调用它。接下来我将尝试将它传递给另一个组件,所以我们将看看它是如何进行的。
标签: javascript arrays json reactjs object