【问题标题】:React: store uploaded array into global variable?反应:将上传的数组存储到全局变量中?
【发布时间】:2020-06-09 12:35:42
【问题描述】:

我目前正在使用 React 上传 CSV 文件并将数据转换为数组,以便我可以访问电话号码。实际上,我几乎完全可以使用它,只有一个问题:我无法弄清楚如何将数组正确存储在全局级别的变量 (dataDump) 中。它将它存储在另一个数组中。

Here's a picture of my console so you can see what I mean.

如果我使用 dataDump[0](如 handleClick 的函数所示),我可以访问 dataDump 的内容,但这不适用于全局变量。我需要能够将数组的值发送到其他组件/文件,所以我认为不必像那样调用它会起作用。可能是我在脑海中过于复杂了,答案非常简单,但在过去的 2-3 周里,我从头开始学习 React、Twilio、Mongodb 等,所以我的大脑不合作。

我将不胜感激!谢谢!代码如下。 (注意这是一个导入到 App 页面的组件。)

import React from "react";
import CSVReader from "react-csv-reader";

var dataDump = [];

console.log(dataDump);


const papaparseOptions = {
  header: true,
  dynamicTyping: true,
  skipEmptyLines: true,
  transformHeader: header => header.toLowerCase().replace(/\W/g, "_"),
  complete: function(results) {
    dataDump.push(results.data);
    console.log(dataDump);
    var rows = results.data;
    let numbers = rows.map(a => a.phone_number); //make the results ONLY the phone numbers
    // console.log(numbers);

    document.getElementById("data2").innerHTML=numbers; //display the phone numbers

       }
     };

class Import extends React.Component {
    constructor(props) {
      super(props);
      this.state = {data:[]};
      this.handleClick = this.handleClick.bind(this);
  }

    handleForce = data => {
        // console.log(data.length);
        console.log(data);
        this.setState({data: data});

    };


    handleClick = () => {
        console.log("success");
        console.log(this.state.data);
        console.log("Next is Numbies:");
        let numbies = dataDump[0].map(a => a.phone_number);
        console.log(numbies);
      document.getElementById("data").innerHTML=numbies;

    }

  render() {
    return (
    <div className="container">
    <CSVReader
      className="csv-input"
      label="Select CSV file to import"
      onFileLoaded={this.handleForce}
      parserOptions={papaparseOptions}

    />
    <div>

    </div>
    <button onClick={this.handleClick.bind(this)}>
        Test
      </button>
      <div id="data" />
      <div id="data2" />
      <div id="data3">
      </div>
    </div>


    );
  }
}

export default Import;
// export default DataController;

【问题讨论】:

标签: javascript arrays reactjs


【解决方案1】:

React-Redux 现在在底层使用上下文和钩子,所以在你已经超越了更简单的 React API 或者至少你已经解决了你的问题之前,不要费心去实现一个 Redux 堆栈。人们开玩笑说 Redux 就像用火箭筒射苍蝇一样。 More info on React-Redux internals herehere's the documentation for React's Context

一些伪代码让你走上正确的道路:

// context.js
import { createContext } from 'react';
export const Store = createContext();

// app.js
import React from 'react';
import { Store } from './context';
import Import from './import'; // I wouldn't change the casing on or reuse a reserved keyword personally, maybe calling this something like 'CsvImporter' would be an improvement 

function App() {
  const [dataDump, setDataDump] = React.useState([]);
  return (
    <Store.Provider value={{ dataDump, setDataDump }}>
      <Import dataDump={dataDump} setDataDump={setDataDump} />
    </Store.Provider>
   );
}

现在你的导入组件有两个新的 props,dataDump 和 setDataDump。您可以像调用任何其他设置状态一样调用 setDataDump。不错!

所以您需要新组件中的 dataDump 吗?这很简单,柠檬挤压,并且没有全局变量或将模块范围扔到一边:

// foobar.js
import React from 'react';
import { Store } from './context';

export function Foobar() {
  // you probably want to do more than force render an array as a string, but this is just a proof of concept
  return (
    <Store.Consumer>
      {({ dataDump, setDataDump }) => (
        <p>
          `${dataDump}`
        </p>
      )}
    </Store.Consumer>
  );
}

只要确保Foobar 或其他组件被呈现为app.js 中Provider 的子级,现在您就有了一个用于传递dataDumps 的“全局”上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多