【发布时间】:2018-09-12 07:41:12
【问题描述】:
我是 React 和 Redux 的初学者。我一直在研究这个项目,我终于弄清楚了如何将数组存储为状态。现在,我遇到的唯一问题是,试图弄清楚如何将该状态传递给另一个文件。
这是两个文件 -Hue.js -ColorShop.js
在 Hue.js 中,我创建了一个 API 并将内容保存到一个名为 productJSON 的对象数组中
Hue.js
class Hue extends React.Component {
constructor() {
super();
this.state = {
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])
}
let productJSON = JSON.stringify(productArray)
this.setState({productJSON: productJSON});
})
}
render() {
return (
<div>
<div className="container2">
{this.state.productJSON}
</div>
</div>
)
}
}
现在,我正在尝试将 productJSON 传递到同一文件夹中的另一个文件 ColorShop.js。我需要用 productJSON 替换 _colors(从静态 json 文件中读取)。
ColorShop.js
import Hue from './Hue.js'
const TIMEOUT = 100
Hue productJSON={this.state.productJSON} <---- my attempt to get it to work
export default { // I need to replace '_colors' with productJSON
getColors: (cb, timeout) => setTimeout(() => cb(_colors), timeout || TIMEOUT),
}
我不想在 ColorShop.js 中创建另一个类,我只想将 this.state.productJSON 导入其中,可以吗?任何指针都非常感谢!
更新:使用了 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(colorArray)
this.setState({productJSON: productJSON});
});
}
render() {
return (
<div>
<div className="container2">
{this.state.productJSON}
</div>
</div>
)
}
}
export default {
getColors: (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.
}
【问题讨论】:
-
使用 Redux 而不是组件状态,你应该在 reducer 中声明状态并在你想要的地方全局访问它。您可以通过 store.getState(); 轻松访问状态
-
否则你可以制作一些包装器,它会调用
fetch并存储你收到的数据,然后将它传递给它的嵌套Color和/或Hue。常见的 React 方法 afaik。
标签: javascript reactjs api components state