javascript - 如何修复基于 JSON 响应的 React 组件填充?

标签 javascript jquery json reactjs

 var prices = [];
      $.getJSON("http://www.asterank.com/api/asterank?query={%22neo%22:{%22$lt%22:%22Y%22},%20%22price%22:{%22$gt%22:100000000}}&limit=1000", function(data) {
        $.each(data, function(key,value) {
          prices.push(value.price);
        });
      });

var App = React.createClass({
   render() {

   return(
     <div className="app">
       <div>
        {console.log("logging price array")}
        {console.log(this.props.priceData)}
        {this.props.priceData.map(p => <PriceColumn price={p} />)}
       </div>
    </div>
   )
  }
});

var PriceColumn = React.createClass({
  render() {
    return(
    <div>
        <h4>{this.props.price}</h4>
    </div>
    )
  }
})

ReactDOM.render(<App priceData={prices}/>, document.getElementById('container'));

我正在尝试使用 json 响应填充 react 组件。这是“this.props.priceData”的 console.log 的一小段

Array[871]
[0 … 99]
0:
525905281.52797025
1:
604514917.0552349
2:
696637551.9520638
3:
875462960.8222823
4:
1267502400
5:
1332894080
6:
1467819274.5386994
7:
1498253120
8:
1703699200
9:
1743786240
10:
1864047360
11:
2725918720
12:
3191380043.7561345
13:
3652885251.1255836
14:
4587566603.506

每次我尝试访问该区域中的数据点时,我都会得到未定义的信息。谢谢您的帮助!

最佳答案

$.getJSON 是异步的,所以当你在 React.render 方法中使用 prices 时,你的回调还没有被执行。更好的方法是让组件自己负责调用,并将返回的价格与回调一起存储在其状态中。例如

var App = React.createClass({
   getInitialState() {
     return {
       priceData: []
     }
   },

   componentWillMount() {
     const apiUrl = "http://www.asterank.com/api/asterank?query={%22neo%22:{%22$lt%22:%22Y%22},%20%22price%22:{%22$gt%22:100000000}}&limit=1000";

     $.getJSON(apiUrl, data => {
        this.setState({
           priceData: data.map(item => item.price)
        });
      });    
   },

   render() {
     return(
       <div className="app">
         <div>
           {this.state.priceData.map(p => <PriceColumn price={p} />)}
         </div>
       </div>
     )
  }
});

var PriceColumn = React.createClass({
  render() {
    return(
    <div>
        <h4>{this.props.price}</h4>
    </div>
    )
  }
})

ReactDOM.render(<App />, document.getElementById('container'));

顺便提一句,通常没有必要在 React 应用程序中使用 JQuery。如果您只将它用于 AJAX 调用,那么您可以使用 browser fetch api使用针对不受支持的浏览器的 polyfill,或更轻量级的库,例如 Axios。

关于javascript - 如何修复基于 JSON 响应的 React 组件填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001126/

相关文章:

javascript - jQuery 中是否有类似 array_unique() 的函数?

php - 来自服务器端处理的 jquery 数据表的空值

javascript - jQuery 悬停在一个克隆的元素上

javascript - JSON.stringify 序列化为 [[]]

javascript - 解析十进制值问题

javascript - 降低鼠标速度

javascript - 从数组中选择和操作单词

javascript - 将经纬度参数发送到 Google map

javascript - Concrete5 和 jVector 贴图

asp.net-mvc - MVC ajax json 发布到 Controller 操作方法