Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中使用AJAX获取服务器数据_Javascript_Jquery_Ajax_Node.js_Reactjs - Fatal编程技术网

Javascript 在React中使用AJAX获取服务器数据

Javascript 在React中使用AJAX获取服务器数据,javascript,jquery,ajax,node.js,reactjs,Javascript,Jquery,Ajax,Node.js,Reactjs,我正在尝试进行AJAX调用,以将服务器数据获取到我的React组件中 我无法用React显示它。我得到这个错误: Uncaught TypeError: Cannot read property 'map' of undefined 我做过调查研究;但是,我不确定如何将它映射到我的react组件 下面是我的代码: var items; $.get("http://localhost:3000/getProducts", function( data ) { items = data;

我正在尝试进行AJAX调用,以将服务器数据获取到我的React组件中

我无法用React显示它。我得到这个错误:

Uncaught TypeError: Cannot read property 'map' of undefined
我做过调查研究;但是,我不确定如何将它映射到我的react组件

下面是我的代码:

var items;
$.get("http://localhost:3000/getProducts", function( data ) {
   items = data;
   this.state.items = data;
});

/*React Code Below */
var RepeatModule = React.createClass({
   getInitialState: function() {
      return { items: [] }
   },
   render: function() {
      var listItems = this.props.items.map(function(item) {
         return (
            <div className='brick'>
               <div>
                  <a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
                  <p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
                  <p className='storeName'>Nike Factory Store</p>
                  <img className='foundPicture' src='../images/rohit.png'/>
               </div>
            </div>
         );
      });

      return (
         <div>
            {listItems}
         </div>
      );
   }
});

ReactDOM.render(<RepeatModule items={items} />,             
   document.getElementById('clothing-content'));

为什么会发生这种错误?它应该如何实现呢?

Javascript是异步的。get函数回调不会阻止程序流,它会在以后执行。其余代码将继续执行。异步发送AJAX请求,然后使用未定义的变量呈现react组件。然后,get请求将在稍后完成并填充数据,但这是在渲染完成后很长一段时间

这里最简单的解决方案是仅在AJAX请求完成后渲染组件:

var RepeatModule = React.createClass({
    render: function() {
        var listItems = this.props.items.map(function(item) {
            return (
                <div className='brick'>
                <div>
                    <a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
                    <p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
                    <p className='storeName'>Nike Factory Store</p>
                    <img className='foundPicture' src='../images/rohit.png'/>
                </div>
                </div>
            );
        });

        return (
            <div>
                {listItems}
            </div>
        );
    }
});

$.get("http://localhost:3000/getProducts", function( data ) {
    ReactDOM.render(<RepeatModule items={data} />,
        document.getElementById('clothing-content'));
});
var RepeatModule=React.createClass({
render:function(){
var listItems=this.props.items.map(函数(项){
返回(

短袖牛津连衣裙衬衫,白色,大号

耐克工厂商店

); }); 返回( {listItems} ); } }); $.get(”http://localhost:3000/getProducts,函数(数据){ ReactDOM.render(, document.getElementById('clothing-content'); });

根据您的需要,更好的解决方案可能是在
componentDidMount
生命周期方法中执行AJAX请求,并将结果存储在state而不是props中。

Javascript是异步的。get函数回调不会阻止程序流,它会在以后执行。其余代码将继续执行。异步发送AJAX请求,然后使用未定义的变量呈现react组件。然后,get请求将在稍后完成并填充数据,但这是在渲染完成后很长一段时间

var RepeatModule = React.createClass({
   getInitialState: function() {
      return { items: this.props.items || [] }
   },
   componentWillMount: function() {
     console.log("componentWillMount()")
     $.get("http://localhost:3000/getProducts", function( data ) {
         this.setState({ items : data })
         console.log(data,"data is here");
      }.bind(this));
   },
   render: function() {
      var listItems = this.state.items.map(function(item) {
         return (
            <ListItem item={item}/>
         );
      });

      return (
         <div>
             {listItems}
         </div>
      );
   }
});
/* make the items stateless */
var ListItem = function(props) {
     return (
         <div className='brick' key={props.item._id}>
         <div>
             <a target='_blank' href={props.item.productURL}><img src={props.item.imageURL}/></a>
             <p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
             <p className='storeName'>Nike Factory Store</p>
             <img className='foundPicture' src='../images/rohit.png'/>
         </div>
         </div>
     );
}
var data = []
ReactDOM.render(<RepeatModule items={data} />, document.getElementById('clothing-content'));
这里最简单的解决方案是仅在AJAX请求完成后渲染组件:

var RepeatModule = React.createClass({
    render: function() {
        var listItems = this.props.items.map(function(item) {
            return (
                <div className='brick'>
                <div>
                    <a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
                    <p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
                    <p className='storeName'>Nike Factory Store</p>
                    <img className='foundPicture' src='../images/rohit.png'/>
                </div>
                </div>
            );
        });

        return (
            <div>
                {listItems}
            </div>
        );
    }
});

$.get("http://localhost:3000/getProducts", function( data ) {
    ReactDOM.render(<RepeatModule items={data} />,
        document.getElementById('clothing-content'));
});
var RepeatModule=React.createClass({
render:function(){
var listItems=this.props.items.map(函数(项){
返回(

短袖牛津连衣裙衬衫,白色,大号

耐克工厂商店

); }); 返回( {listItems} ); } }); $.get(”http://localhost:3000/getProducts,函数(数据){ ReactDOM.render(, document.getElementById('clothing-content'); });
根据您的需要,更好的解决方案可能是在
componentDidMount
生命周期方法中执行AJAX请求,并将结果存储在state而不是props中。

var RepeatModule=React.createClass({
var RepeatModule = React.createClass({
   getInitialState: function() {
      return { items: this.props.items || [] }
   },
   componentWillMount: function() {
     console.log("componentWillMount()")
     $.get("http://localhost:3000/getProducts", function( data ) {
         this.setState({ items : data })
         console.log(data,"data is here");
      }.bind(this));
   },
   render: function() {
      var listItems = this.state.items.map(function(item) {
         return (
            <ListItem item={item}/>
         );
      });

      return (
         <div>
             {listItems}
         </div>
      );
   }
});
/* make the items stateless */
var ListItem = function(props) {
     return (
         <div className='brick' key={props.item._id}>
         <div>
             <a target='_blank' href={props.item.productURL}><img src={props.item.imageURL}/></a>
             <p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
             <p className='storeName'>Nike Factory Store</p>
             <img className='foundPicture' src='../images/rohit.png'/>
         </div>
         </div>
     );
}
var data = []
ReactDOM.render(<RepeatModule items={data} />, document.getElementById('clothing-content'));
getInitialState:函数(){ 返回{items:this.props.items | |[]} }, componentWillMount:function(){ log(“componentWillMount()”) $.get(”http://localhost:3000/getProducts,函数(数据){ this.setState({items:data}) 日志(数据,“数据在这里”); }.约束(这个); }, render:function(){ var listItems=this.state.items.map(函数(项){ 返回( ); }); 返回( {listItems} ); } }); /*使项目无状态*/ 变量ListItem=函数(道具){ 返回(

短袖牛津连衣裙衬衫,白色,大号

耐克工厂商店

); } var数据=[] ReactDOM.render(,document.getElementById('countain-content');
我必须绑定数据并使用componentWillMount

var RepeatModule=React.createClass({
getInitialState:函数(){
返回{items:this.props.items | |[]}
},
componentWillMount:function(){
log(“componentWillMount()”)
$.get(”http://localhost:3000/getProducts,函数(数据){
this.setState({items:data})
日志(数据,“数据在这里”);
}.约束(这个);
},
render:function(){
var listItems=this.state.items.map(函数(项){
返回(
);
});
返回(
{listItems}
);
}
});
/*使项目无状态*/
变量ListItem=函数(道具){
返回(

短袖牛津连衣裙衬衫,白色,大号

耐克工厂商店

); } var数据=[] ReactDOM.render(,document.getElementById('countain-content');

我必须绑定数据并使用componentWillMount

@AndyRay我的get请求应该在我的初始状态函数中吗?@AndyRay我的get请求应该在我的初始状态函数中吗?你能详细说明在componentDidMount生命周期方法中执行请求的优点吗?嗯,我仍然得到未捕获的TypeError:无法在get回调中读取未定义的errorLog
数据的属性“map”,以确保它已填充。我实际上没有得到TypeError,但它看起来好像未填充。我必须绑定它吗?re:您能详细说明在componentDidMount生命周期方法中执行请求的优点吗?嗯,奇怪的是,我仍然得到未捕获的类型错误:无法读取属性“map”o