Javascript React变量会更改,但不会呈现。。。为什么?

Javascript React变量会更改,但不会呈现。。。为什么?,javascript,reactjs,Javascript,Reactjs,我是React的新手,以下代码有问题: import React, { Component } from 'react'; import banner from './images/banner.png'; import logo from './images/logo.png'; import coin from './images/coin.png'; import './App.css'; var $ = require('jquery'); function CardItem(pro

我是React的新手,以下代码有问题:

import React, { Component } from 'react';
import banner from './images/banner.png';
import logo from './images/logo.png';
import coin from './images/coin.png';
import './App.css';
var $ = require('jquery');


function CardItem(props) {
  return (
                    <li>
                        <div className="imageWrapper">
                            <img/>
                        </div>
                        <h3>Title</h3>
                        <p>Category</p>

                    </li>
  );
}


class Cards extends Component {

  constructor() {
    super();

    let items = [];
    this.items = items;

     $.ajax({
      url: '//localhost:3004/products',
      dataType: 'json',
      success: function(data) {

       items.push(data);

      },
      error: function(xhr, status, err) {
         console.log("\nError:" + err);

      }
    });
  }

    render(){


        var itemsList = this.items.map(function(oneItem){

            return <CardItem/>;
        });



        return (

                <section>
                    <h2>{this.items.length} Products</h2>

                    <ul>
                {itemsList}     

                    </ul>
                </section>
        );
    }
}


class App extends Component {
  render() {
    return (


        <div className="App">
            <header>
                <img className="logo" src={logo}/>
                <img className="banner" src={banner}/>


            </header>

            <Cards/>

        </div>


    );
  }
}

export default App;
import React,{Component}来自'React';
从“./images/banner.png”导入横幅;
从“./images/logo.png”导入徽标;
从“./images/coin.png”导入硬币;
导入“/App.css”;
var$=require('jquery');
功能卡片(道具){
返回(
  • ); } } 导出默认应用程序;
  • 假设web浏览器应该显示数组
    项的列表
    ,但相反,它什么也不显示,就像数组是空的一样


    当回调更改变量
    items
    时,我在浏览器中看到的内容不会更新。我做错了什么?

    我看到两个问题:

  • items.push(data)
    实际上会将产品数组作为一个项目附加到您的
    items
    数组中。改用
    this.items=this.items.concat(数据)

  • 当收到数据时,需要重新渲染组件。因此,我最好将项目保持在组件状态:在成功回调中调用
    this.setState({items:data})
    (这将触发重新呈现),并在
    render()
    方法中使用
    this.state.items
    ,而不是
    this.items

  • 正如Rohitas所说,在
    componentDidMount

    因此,您的
    组件可能类似于:

    import fetch from 'cross-fetch';
    
    // ...
    
    class Cards extends Component {
    
      constructor() {
        super();
        this.state = {
          items: [],
        };
      }
    
      componentDidMount() {
        fetch('//localhost:3004/products')
          .then(res => {
            if (res.status >= 400) {
              console.error('Unable to fetch products', res);
            } else {
              res.json()
                .then(items => this.setState({ items });
            }
          });
      }
    
      render() {
        return (
          <section>
            <h2>{this.state.items.length} Products</h2>
            <ul>
              {this.state.items.map(item =>
                <CardItem {...item} />)}
            </ul>
          </section>
        );
    }
    
    从“交叉提取”导入提取;
    // ...
    类卡扩展组件{
    构造函数(){
    超级();
    此.state={
    项目:[],
    };
    }
    componentDidMount(){
    获取('//localhost:3004/products')
    。然后(res=>{
    如果(分辨率状态>=400){
    console.error('无法获取产品',res);
    }否则{
    res.json()
    .then(items=>this.setState({items});
    }
    });
    }
    render(){
    返回(
    {this.state.items.length}产品
    
      {this.state.items.map(item=> )}
    ); }
    不要使用Jquery AJax…使用一些npm包,如request或Axio所有AJax调用都将在componentDidMountHi Dmitry中进行!感谢您的帮助!我不确定,但我认为我做错了什么,因为我在浏览器中遇到了以下错误:
    类型错误:this.state.items.map不是功能卡。render src/App.js:119 116|117{this.state.items}产品118{ul>>119{this.state.items.map(item=>120}}121}122}
    @Captain
    res.json()
    返回承诺。我刚刚修复了示例。还要确保您的
    /products
    端点返回列表,否则您还需要额外的步骤从返回的数据中提取列表完美!成功了!非常感谢,@Dmitry。您的帮助非常宝贵!