将对象道具传递到子组件,并且在访问/渲染时遇到问题

时间:2019-06-27 02:17:16

标签: reactjs object properties

我目前正在尝试通过道具将对象传递给孩子并呈现一个列表。我可以控制台记录数据,但是无法迭代/渲染对象。

我的对象的格式为:

  

光谱:[{名称:ID:数据:},]

我尝试使用对象键/条目和映射,但是这些键返回空数组。在子组件中为prop使用深色副本似乎也不起作用。我以为我的问题在于传递道具的方式?在子组件中似乎无法枚举。

我在importCSV中设置了父状态(以及传递给孩子的道具数据)。我可以在控制台上记录我将状态设置为的数据,但是我无法从它们之一访问它。我也无法获得数组的长度。

我可以管理日志this.props.AppState,但除此之外我无能为力。

更新: 这似乎是设置状态的异步问题?我该如何解决?

import React, { Component } from 'react';
import FileReader from './FileReader';
import NLC from './nlc.js';
import LightBox from './LightBox';
import './App.css';
import ViewArea from './ViewArea';
var Papa = require("papaparse/papaparse.min.js");

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {
        counter: 0,
        spectra: []
      }
    }
    this.handleChange = this.handleChange.bind(this);
    this.importCSV = this.importCSV.bind(this);
    //reference for input data
    this.AppRef = React.createRef();
  }

  //brought up from file reader
  importCSV = () => {
    const csvArray = this.AppRef.current.files;
    const counter = this.AppRef.current.files.length;
    var spectdict = [];


    //parse like normal
    var filecount = 0;
    for (let i = 0; i < counter; i++) {
      Papa.parse(csvArray[i], {
        complete: function (result, file) {
          spectdict.push({
            id: filecount++,
            name: file.name,
            data: result.data
          })
          filecount++;
        },
        skipEmptyLines: true,
        error: this.CSVParseError
      });
    }
    //set the state for all children
    //JSON.stringify(spectdict);
    console.log(spectdict);
    this.setState({
      data: {
        counter: counter,
        spectra: spectdict
      }
    })
  };

  CSVParseError = function (err, csvfile) {
    if (csvfile === undefined) {
      alert("Unable to process CSV file, please verify the file can be accessed and try again. Error reason was: " + err.code);
    }
  }

  handleChange = event => {
    //console.log(this.AppRef.current.files[0]);
  };

  render() {

    return (

      <div className="App">

        <header className="App-header">
          <h1 className="App-title">IR</h1>
          <ViewArea AppState={this.state.data} />
          <FileReader AppState={this.state.data} AppRef={this.AppRef} importCSV={this.importCSV} handleChange={this.handleChange} />
          <LightBox AppState={this.state.data} />
          <NLC AppState={this.state.data} />
        </header>
      </div>

    );
  }
}

export default App;


//view area

class ViewArea extends React.PureComponent {


    state = {
        spectra: [],
        counter: 0
    }

    static getDerivedStateFromProps(props, state) {
        // Any time the current user changes,
        // Reset any parts of state that are tied to that user.
        // In this simple example, that's just the email.
        if (props.AppState.spectra !== state.spectra) {
            return {
                spectra: props.AppState.spectra,
                counter: props.AppState.counter
            };
        }
        return null;
    }

    render() {
        const spectra = this.state.spectra;
        var content = <p>here</p>;
        if (this.state.counter > 0) {
            console.log(spectra);
            content = spectra.map((item, key) =>
                <li key={item.id}>{item.name}</li>
            );
        } else {
            console.log('not');
        }
        return (
            <div>
                <ul>{content}</ul>
            </div>
        );
    }
};

export default ViewArea;

//file reader component

class FileReader extends Component {
  constructor() {
    super();
    this.state = {
    };

  }
  render() {
    return (
      <div className="App">
        <h2> Import CSV File </h2>

        <input
          className="csv-input"
          type="file"
          multiple
          accept='.csv'
          ref={this.props.AppRef}
          name="file"
          placeholder={null}
          onChange={this.props.handleChange}
        />
        <p />
        <button onClick={this.props.importCSV}> Upload </button>
      </div>
    );
  }
}

export default FileReader;

0 个答案:

没有答案