Невозможно прочитать свойство 'map' из undefined для отображения данных для React Table - PullRequest
0 голосов
/ 13 марта 2020

Я создаю таблицу в React, которая отображает набор данных, и у меня возникла проблема с отображением данных из SupplierList. js.

Приложение. js

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import SupplierList from './components/SupplierList';


const supplierList = [
{id: 1, category: 1, name:'Company 1', address: 'Address 1', phone: '(336)-693-5580', email: 'email 1'},
{id: 2, category: 2, name:'Company 2', address: 'Address 2', phone: '(336)-693-5580', email: 'email 2'},
{id: 3, category: 3, name:'Company 3', address: 'Address 3', phone: '(336)-693-5580', email: 'email 3'},
{id: 4, category: 4, name:'Company 4', address: 'Address 4', phone: '(336)-693-5580', email: 'email 4'}
];

if(localStorage.getItem("suppliers") === null) {
  localStorage.setItem('suppliers', JSON.stringify(supplierList));
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      supplierList: []
    }
    this.editSupplierSubmit = this.editSupplierSubmit.bind(this);
    this.deleteSupplier = this.deleteSupplier.bind(this);
    this.addNewSupplier = this.addNewSupplier.bind(this);
  }
  componentWillMount() {
    let supplierList = JSON.parse(localStorage.getItem("suppliers"));
    this.setState((prevState, props) => ({
      supplierList: supplierList
    }));
  }
  addNewSupplier() {
    this.setState((prevState, props) => ({
      supplierList: [...prevState.supplierList, {  
        id: Math.max(...prevState.supplierList.map(function(o){
          return o.id
        })) + 1, category: '', name: '', address: 1, phone: '', email: ''
      }]
    }));
  }
  deleteSupplier(id) {
    let r = window.confirm("Do you want to delete this item");
    if (r === true) {
      let filteredSupplierList = this.state.supplierList.filter(
        x => x.id !== id
      );
       this.setState((prevState, props) => ({
          supplierList: filteredSupplierList
       }));
       localStorage.setItem(
         'suppliers',
         JSON.stringify(filteredSupplierList)
       );
    }
  }
  editSupplierSubmit(id, category, name, address, phone, email) {
    let supplierListCopy = this.state.supplierList.map((supplier) => {

      if (supplier.id === id) {
        supplier.category = category;
        supplier.name = name;
        supplier.address = address;
        supplier.phone = phone;
        supplier.email = email;
      }
      return supplier;
    });
    this.setState((prevState, props) => ({
      supplierList: supplierListCopy
    }));
    localStorage.setItem(
      'suppliers',
      JSON.stringify(supplierListCopy)
    );
  }
  render() {
    return (
      <div className="container-fluid">
        <div className="row mt-3"><div className="col-lg-12">
          <div className="card">
            <div className="card-header">
              List of Company'\s' Suppliers
            </div>
            <div className="card-body">
              <table className="table table-hover">
                <thead className="thead-dark"><tr><th>Category</th><th>Name</th><th>Address</th><th>Phone</th><th>Email</th><th>Edit/Save</th><th>Delete</th></tr></thead>
                <SupplierList
                  deleteSupplier={this.deleteSupplier}
                  supplierList={this.state.SupplierList}
                  editSupplierSubmit={this.editSupplierSubmit}
                />
              </table>
            <button
              className="btn btn-dark pull-left"
              onClick={this.addNewSupplier}>
              Add New
            </button>
          </div>
        </div>
      </div>
     </div>
    </div>
   );
  }
}
export default App;

SupplierList. js

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

export default class SupplierList extends Component {
  render() {
    let suppliers = this.props.supplierList;
    const trItem = suppliers.map((item, index) => (
      <SupplierItem
        key={index}
        supplier={item}
        index={index}
        editSupplierSubmit={this.props.editSupplierSubmit}      
        deleteSupplier={this.props.deleteSupplier}
      />
    ));
    return <tbody>{trItem}</tbody>;
  }
}

Я получаю сообщение об ошибке TypeError: Невозможно прочитать свойство map of undefined ошибка, и я застрял с этой проблемой в течение нескольких часов. Я искал во всем своем коде, чтобы найти все опечатки или что-то, что я набрал неправильно, насколько мне известно. Если есть кто-нибудь, кто может помочь решить проблему, я был бы очень признателен.

1 Ответ

0 голосов
/ 13 марта 2020

в parent: supplierList = {this.state. S upplierList}

должно быть supplierList={this.state.supplierList}

this.state.SupplierList не определено из-за опечатки.

undefind не имеет метода сопоставления.

Чтобы увидеть этот журнал в дочернем

...