列表中的数据在初始加载时不显示

时间:2019-02-03 12:17:51

标签: reactjs react-router

我正在尝试创建一个应用程序,该应用程序的主页上将显示项目列表。

我已经有一些预定义的数据要显示;它在App.js中进行了硬编码。这是结构(您应该主要关注render()方法):

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import './App.css';
import Details from './components/Details';
import NewItem from './components/NewItem';
import List from './components/List';

const item0 = {
  id: 0,
  img_url: "https://static.adweek.com/adweek.com-prod/wp-content/uploads/2018/10/Screen-Shot-2018-10-17-at-1.25.22-PM.png",
  name: "Burger0",
  price: "10.60$",
  description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed accumsan neque. Donec at nunc congue, iaculis justo vel, iaculis est. Vestibulum sit amet mauris a erat pulvinar dignissim. Duis finibus consequat fermentum. Pellentesque vulputate metus quis erat cursus, at consectetur libero euismod. Proin convallis maximus mi, ac sollicitudin velit."
}

const item1 = {
  id: 1,
  img_url: "https://static.adweek.com/adweek.com-prod/wp-content/uploads/2018/10/Screen-Shot-2018-10-17-at-1.25.22-PM.png",
  name: "Burger1",
  price: "10.60$",
  description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed accumsan neque. Donec at nunc congue, iaculis justo vel, iaculis est. Vestibulum sit amet mauris a erat pulvinar dignissim. Duis finibus consequat fermentum. Pellentesque vulputate metus quis erat cursus, at consectetur libero euismod. Proin convallis maximus mi, ac sollicitudin velit."
}

const item2 = {
  id: 2,
  img_url: "https://static.adweek.com/adweek.com-prod/wp-content/uploads/2018/10/Screen-Shot-2018-10-17-at-1.25.22-PM.png",
  name: "Burger2",
  price: "10.60$",
  description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sed accumsan neque. Donec at nunc congue, iaculis justo vel, iaculis est. Vestibulum sit amet mauris a erat pulvinar dignissim. Duis finibus consequat fermentum. Pellentesque vulputate metus quis erat cursus, at consectetur libero euismod. Proin convallis maximus mi, ac sollicitudin velit."
}

const items = [item0, item1, item2];

class App extends Component {
  addItemToList = item => {
    items.push(item);
  }

  toogleMenu = () => {
    let x = document.getElementById("myLinks");
    if (x.style.display === "block") {
      x.style.display = "none";
    } else {
      x.style.display = "block";
    }
  }

  render() {
    const toList = {
      pathname: "/",
      items: items
    }
    const toNewItem = {
      pathname: "/newitem/",
      addItemToList: this.addItemToList,
      listSize: items.length
    }

    return (
      <Router>
        <div className="container">
        <div className="topnav">
          <a href="#home" className="active">Logo</a>
          <div id="myLinks">
            <Link to={toList}>List</Link>
            <Link to={toNewItem}>New Item</Link>
          </div>
          <a href="javascript:void(0);" className="icon" onClick={this.toogleMenu}>
            <i className="fa fa-bars"></i>
          </a>
        </div>
        <Switch>
            <Route path="/newitem/" component={NewItem} />
            <Route path="/details/" component={Details} />
            <Route path="/" component={List} />
        </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

但是,列表中的数据不会在初始加载时显示-我只能看到顶部的导航栏和下面的空白区域。在加载时如何显示数据,而且每次我转到路径名“ /”时如何显示数据?

加载后,我必须打开菜单,单击“列表”,然后数据才能正常显示。我该如何实现这种情况默认发生?

更新

列表的实现

import React, { Component } from 'react';
import ListItem from './ListItem';

class List extends Component {    
    populateList = () => {
        return this.props.location.items.map((el, i) => {
            return (
            <ListItem key={i} item={el} />
            );
        });
    }

    render() {
        if (this.props.location.items === undefined) {
            return <ul className="list"></ul>
        }
        return(
            <ul className="list">
                {this.populateList()}
            </ul>
        );
    }
}

export default List;

要加载的数据位于App.js中,因为我还可以选择添加新项目,并且找不到其他更新项目列表的方法。如果可以将数据放置在List.js中,并且添加新项后更新List.js的状态,那将是完美的。

1 个答案:

答案 0 :(得分:1)

您问题中的List的实现通过items道具接收location数据。首次加载应用程序时,应用程序的URL可能是https://my.app.com/(根目录),因此没有List要显示的项目数据。

我会这样解决:

1)修改List,使其可以独立于路径接收items,例如

import React, { Component } from 'react';
import ListItem from './ListItem';

class List extends Component {    
    let items = [];
    populateList = () => {
        if (this.props.items) {
            this.items = this.props.items;
        } else { // No items via prop
           this.props.location.items.map((el, i) => {
            this.items.push(el)
           });
         }
    }

    render() {
        this.populateList()
        if (!this.items) {
            return <ul className="list"></ul>
        }
        return(
            <ul className="list">
                {this.items.map((el, i) =>
                  <ListItem key={i} item={el} />
                 }
            </ul>
        );
    }
}

export default List;

2)修改“ /”路由为

        <Route path="/" render={() => <List items={items}/>} />

上面的代码仅供参考,未经测试。