【问题标题】:React.js - array not displaying correctly after getting strings from textfileReact.js - 从文本文件中获取字符串后数组无法正确显示
【发布时间】:2018-10-30 15:33:30
【问题描述】:

我正在使用 React.js 编写程序,但无法正确显示数组。我尝试了各种“加入”语句,但似乎都没有奏效。我尝试使用 split(/\r?\n/) 来拆分行。 我正在使用 Fetch API 调用文本文件,然后将内容放入一个数组中,然后我想将其显示到屏幕上。如果有人可以就为什么它可能无法正常工作提供任何指示,请指出!

这是我的代码:

cats.txt

Persian
Himalayan
Siamese
Sphynx

App.js

import React, { Component } from 'react';
import "Cat" from "./components/Cat.js";
import catFile from "cats.txt";

class App extends Component {
  state = {
      cat_Array: []
    }
    getCats = (e) => {
      e.preventDefault();
        fetch(catFile).then(data => data.text()),
        .then(allResponses => {
          let catArray = allResponses.split(/\r?\n/);
this.setState({
                    cat_array: catArray
                  })
            }
          }
        })
      }
  render() {
    return (
      <div>
      <h2> Cats</h2>
      <Cats
        getCats={this.getCats}
        />

      </div>
    );
  }
}

组件/Cat.js

import React from 'react';

class Cat extends React.Component {
    render() {
        return (
            <div>
               <p> {this.props.getCats} </p>
            </div>)
    }
}

export default Cat;

实际输出

PersianHimalayanSiameseSphynx

预期输出

Persian
Himalayan
Siamese
Sphynx

【问题讨论】:

  • 你只是转储了一系列猫。也许你应该迭代并把每个放在一个 div 或一个列表等中。

标签: javascript arrays reactjs iterator fetch-api


【解决方案1】:

我添加了几行代码并获得了您想要的输出。更改以下内容 -

用这个替换fetch的主体-

  fetch(catFile)
    .then(data => data.text())
    .then(allResponses => {
      let catArray = allResponses.split('\n');
      this.setState({
           cat_Array: catArray
       });
   });

render()方法中添加这段代码-

const catData = this.state.cat_Array.map((data) => {
      return (
        <span>{data} <br/></span>
      )
    });

现在将 castData 作为道具传递给 Cat 组件,而不是调用 this.props.getCats。所以现在你可以像这样直接显示数据了 - {catData}

希望你明白了。

【讨论】:

  • 非常感谢!
  • 不客气!如果问题解决了问题,您可以将其标记为已接受。会对其他人有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多