本文介绍了Papa.parse componentDidMount应该ComponentUpdate混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我认为这是codeandbox的CORS问题,但是我还没有弄清楚如何使用静态ip甚至本地主机托管.当我可以确认这是papaparse和codeandbox cloud ide之间的CORS问题时,我将进行更新.我开始了一个新问题一个与Domino在同一个papaparse应用程序上解决的问题不同的问题

I think this is a CORS issue with codesandbox, but I haven't figured out how to host with static ip or even localhost yet. I'll update when I can confirm it is a CORS issue between papaparse and codesandbox cloud ide. I started a new question for a different problem than Domino solved here on the same papaparse application

StackOverflow上的这个问题是我与 Papa.parse 的对话的扩展.

This question here on StackOverflow is an extension of my conversation with Papa.parse.

此处找到了一种模式,类似地,我使用了this.function通过"City"参数&解析的每个对象尝试为每个城市渲染一个"WeatherCitySkyMap"组件.如果我硬编码让city = [{city:"New York"},{city:"Baltimore"}];但我想要城市,则渲染后的代码已经过测试,可以为城市数组中的每个城市渲染这样的组件.从我在北美的csv城市列表的dropbox链接中解析的每个城市,将由Papa.parse步骤填充.

A pattern is found here, similarly I use a this.function to pass down every object as it is parsed with "City" parameter & try to render a "WeatherCitySkyMap" component for each City. The code after render has been tested to render such a component for each City in the cities array if I hard code let cities = [{ city: "New York" }, { city: "Baltimore" }];, but I want cities to be populated by Papa.parse step for each City parsed from my dropboxlink of a csv list of cities in NorthAmerica.

class CitiesMap extends React.Component {
  constructor(props) {
    super(props);
    this.updateData = this.updateData.bind(this);
  }
  componentDidMount() {
    Papa.parse(
      "https://cors-anywhere.herokuapp.com/https://www.dropbox.com/s/5vcoo9r60hgczd1/worldcitiespop_northamerica_nolonglat.csv?dl=1",
      {
        download: true,
        header: true,
        worker: true,
        skipEmptyLines: true,
        step: this.updateData,
        complete: function() {
          console.log("all done");
        }
      }
    );
  }
  updateData(results) {
    cities.push(results.data, ["City"]);
    this.setState({ cities });
  }
  render(props) {
    let filteredCities = cities.filter(cities => {
      return (
        cities.City.toUpperCase().indexOf(this.props.search.toUpperCase()) !==
        -1
      );
    });
    return (
      <div>
        <div className="Cities">
          {filteredCities.map(City => {
            return (
              <div>
                <WeatherCitySkyMap
                  description={this.description}
                  humidity={this.humidity}
                />
                {JSON.stringify([City])
                  .replace(/[^\w\s]/g, "")
                  .replace(/(city)/g, "")}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default CitiesMap;

在此找到此模式"链接使用UNSAFE_componentWillMount(),相反,我尝试在Papa.parse周围使用componentDidMount(),但需要Papa.parse results.data在它们像componentWillMount()那样呈现之前发生完成(或者我应该在某处使用shouldComponentUpdate& forceUpdate()吗?).我读到的最佳实践是用构造函数和super替换componentWillMount,所以我应该把Papa.Parse放在构造函数中吗?我尝试了,迷路了.感谢您阅读和阅读您的帮助.

"This pattern is found here" link uses UNSAFE_componentWillMount()), instead I try to use componentDidMount() around Papa.parse, but need the Papa.parse results.data to happen before they render like componentWillMount() would have done (or should I use shouldComponentUpdate & forceUpdate() somewhere?). I read best practices is to replace componentWillMount with constructor and super, so should I put Papa.Parse in the constructor? I tried that and got lost. Thanks for reading & your help in advance.

在Domino987回答后更新(到目前为止):

UPDATE after Domino987 answer (so far):

import React from "react";
import WeatherCitySkyMap from "./WeatherCitySkyMap";
import Papa from "papaparse";

import ".././Explore/Cities.css";

class CitiesMap extends React.Component {
  constructor(props) {
    super(props);
    this.updateData = this.updateData.bind(this);
    this.state = { cities: [] };
  }
  componentDidMount() {
    Papa.parse( "https://dl.dropboxusercontent.com/s/k81s5enbamijuke/worldcitiespop_northamerica_nolonglat_few.csv?dl=0",
      {
        download: true,
        header: true,
        worker: true,
        skipEmptyLines: true,
        step: this.updateData,
        complete: function() {
          console.log("all done");
        }
      }
    );
  }
  updateData(results) {
    this.setState(prevState => ({
      cities: [...prevState.cities, results.data.City]
    }));
  }
  render(props) {
    let filteredCities = this.state.cities.filter(cities => {
      return (
        cities.toUpperCase().indexOf(this.props.search.toUpperCase()) !==
        -1
      );
    });
    return (
      <div>
        <div className="Cities">
          {filteredCities.map(City => {
            return (
              <div>
                <WeatherCitySkyMap
                  description={this.description}
                  humidity={this.humidity}
                />
                {JSON.stringify([City])
                  .replace(/[^\w\s]/g, "")
                  .replace(/(city)/g, "")}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default CitiesMap;

推荐答案

因此,对于组件的工作方式存在一些误解:

So there are a few misconceptions of how the component works:

  1. 道具不传递给渲染:您可以使用this.props访问它们.
  2. 开始时本地状态为null:在构造函数中写入this.state = {cities: []},如果您尝试访问render中的城市,这将防止破坏代码.
  3. 要访问渲染和updateData中的城市,请使用this.state.cities.这样您就可以访问当前的城市.
  4. 要在状态内更新数组,请像下面这样编写:this.setState(prevState => { cities: [...prevState.cities, results.data.City] });.这将更新状态不变,并保留以前的城市.
  1. Props are not passed to render: You can access them with this.props.
  2. Local state is null at beginning: in your constructor write this.state = {cities: []}, This will prevent breaking your code if you try to access cities within render.
  3. To access cities in your render and updateData use this.state.cities. This will let you access the current cities.
  4. To update an array within the state write it like this: this.setState(prevState => { cities: [...prevState.cities, results.data.City] });. This will update the state immutable and will keep the previous cities.

componentDidMount是实现服务器调用,副作用或Papa.parse的正确方法.它将首先呈现不包含数据的组件,但是一旦存在数据,它将对其进行更新.该组件不会损坏,因为对于点2,状态将不会为null,并且渲染仍将起作用.

componentDidMount is the correct way to implement a server call, side effect or Papa.parse. It will render the component without data first, but as soon as data is present, it will update it. The component will not break, because with point 2 the state will not be null and the render will still work.

我希望这些评论能帮助您使代码正常工作.

I hope these remarks will help you get your code working.

//编辑由于您询问如何实现updateData和呈现,因此下面是一些代码:

// EditSince you ask how to implement updateData and render, here is some code:

updateData(results) {
  // This will not work because cities is not defined here (us this.state.cities) and you mutate the data with push
  // cities.push(results.data.city);
  // I am not sure why you add "City" but that is in your code
  this.setState(prevState => { cities: [...prevState.cities, results.data.City]});
}
render(props) {
  // Filter will check each city in the cities array, so you have to write it like this:
  const filteredCities = this.state.cities.filter(city => city.indexOf(this.props.search.toUpperCase()) !== -1);
}

快乐的编码.

这篇关于Papa.parse componentDidMount应该ComponentUpdate混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:07