[英]How to access variable inside React Component? Initialized it outside Component
我目前是在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)
}
let productJSON = [] //initialize productJSON array here
class Hue extends React.Component {
constructor() {
super();
this.state = {
elements: [],
productJSON: []
};
}
componentDidMount() {
fetch('numberendpoint.json')
.then(res => {
this.setState({elements: res.data});
})
}
render() {
if(this.state.elements.length > 0){ //once the data is fetched
return (
<div>
<div className="container2">
{this.state.elements.map((rainbow) => {
return (
<div key={rainbow.results}>
<p>{raindow.color}</p>
<p>{rainbow.value}</p>
</div>
)
})}
</div>
</div>
)
}
else{ // initial render
return null;
}
}
我真的不明白为什么您要尝试将一个类的数组放到外面,但是我认为您需要了解何时在React中调用每个事件。
componentDidMount
是一个事件,当所有组件都安装在类中时会被调用。 因此,在此阶段, render()
函数已经运行。 这意味着您的productJSON
在此阶段未定义。 您真正想做的是确保在状态更新为undefined
其他内容时更改组件。
请尝试以下代码。
let productJSON = [] //initialize productJSON array here
class Hue extends React.Component {
constructor() {
super();
this.state = {
elements: [],
};
}
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])
}
this.setState({productJSON:colorArray});
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.productJSON ? 'state not ready' : this.state.productJSON} //this is the important part. It will render this.state.productJSON only when it is a truthy value.
</div>
</div>
)}
}
假设您确实从调用中获得了一个有效的colorArray
,那么它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.