如何将JSON对象另存为数组然后将其传递给React组件?

时间:2018-05-25 15:44:55

标签: json reactjs asynchronous fetch

基本上,我想这样做:

var PRODUCTS = []

fetch('https://api.myjson.com/bins/10scuq')
  .then(res => res.json())
  .then(data => PRODUCTS = data)

const container = document.getElementById('root')

render (
  <FilterableProductTable products={PRODUCTS}/>,
  container
)

而不是这样做:

const PRODUCTS = [
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

ReactDOM.render(
  <FilterableProductTable products={PRODUCTS} />,
  document.getElementById('root')
);

第一段代码最终将一个空数组传递给组件,第二段工作。

我不想使用this.setState()。我根本不想触摸组件的内部。在使用fetch()时,还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

这是一种丑陋的方式这样做:)正如评论中所说,如果你使用React,请考虑React方式。

for a in questoes.alternativas_set.all():

答案 1 :(得分:-2)

尝试将数据推送到PRODUCTS数组

var PRODUCTS = []
fetch('https://api.myjson.com/bins/10scuq')
 .then(res => res.json())
 .then(data => PRODUCT.push(data)
);