首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有异步值的设置状态

具有异步值的设置状态
EN

Stack Overflow用户
提问于 2018-09-15 17:06:49
回答 1查看 159关注 0票数 0

我试图获取React组件的数据,并将其设置为状态下的嵌套对象:

代码语言:javascript
复制
import React from 'react';
import './App.css';
import XLSX from "xlsx";

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      isLoading:false,
      cards:{}
    }
  }

  componentDidMount(){
    this.setState({isLoading:true});

    /* convert xlsx to JSON */
    fetch("../data/Cards_v0.1.xlsx")
    .then((d)=> d.arrayBuffer()).then((d)=>{

      const data = new Uint8Array(d);
      const workbook = XLSX.read(data, {type:"buffer"});
      const sheet = workbook.Sheets["Deck"];
      const cardsJSON = XLSX.utils.sheet_to_json(sheet,{range:1});

      let cards = {};
      for(let i=0; i<cardsJSON.length; i++){
        for(let j=0; j<cardsJSON.length; j++){
          cards[cardsJSON[i].Name] = cardsJSON[i];
        }
      }
      this.setState({cards:cards, isLoading:false});
  });
  }

  render() {
    if(this.state.isLoading){
      return <div>Loading</div>;
    }
    return (
      <div>
        { this.state.cards.Single.Name }
      </div>
    );
  }
}

export default App;

React显示对象处于状态,cards>Single>Name为“单”,但{this.state.cards.Single.Name}抛出TypeError:无法读取未定义的.的属性'Name‘

最让我困惑的是,{this.state.cards.Single}抛出对象作为React子对象是无效的(找到:带有键{Name、Type、稀有性、文本、货币}的对象)。如果您打算呈现一个子集合,请使用数组代替.

所以键Name是在没有被调用的时候找到的,但是当我调用它时,对象就变得没有定义了?

很困惑。任何帮助都是非常感谢的!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-15 20:19:36

{this.state.cards.Single} React不知道如何显示对象,因此 将抛出

你也有一些奇怪的选择设置反应状态。由于组件总是要在挂载上获取数据,所以让isLoading默认为true,然后在成功的fetch响应中设置为false更有意义。

我不知道您的cardsJSON是如何构造的,但是下面的示例展示了两种显示嵌套JSON的方法。

  • 将其封装在pre中,编写html元素并使用JSON.stringify(obj, replacer, spaces)
  • this.state.cards中解构对象属性(如果其中任何属性也是嵌套对象,那么也需要对它们进行析构!)然后在表、列表等中显示所有已销毁的数据。

工作示例:https://codesandbox.io/s/km3wwvqqzv

Example.js

代码语言:javascript
复制
import React, { Component, Fragment } from "react";
import DisplayCode from "./displayCode";
import DisplayList from "./displayList";

export default class Example extends Component {
  state = {
    isLoading: true,
    cards: {}
  };

  componentDidMount = () => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then(response => response.json())
      .then(json => this.setState({ cards: json, isLoading: false }));
  };

  render = () =>
    this.state.isLoading ? (
      <div>Loading</div>
    ) : (
      <Fragment>
        <DisplayCode cards={this.state.cards} />
        <DisplayList cards={this.state.cards} />
      </Fragment>
    );
}

displayCode.js

代码语言:javascript
复制
import React, { Fragment } from "react";

export default ({ cards }) => (
  <Fragment>
    <h3>Display JSON as code:</h3>
    <pre style={{ height: 300, overflowY: "auto" }}>
      <code>{JSON.stringify(cards, null, 4)}</code>
    </pre>
  </Fragment>
);

displayList.js

代码语言:javascript
复制
import map from "lodash/map";
import React, { Fragment } from "react";

export default ({ cards }) => (
  <Fragment>
    <h3 style={{ marginTop: 30 }}>Display JSON as list:</h3>
    <ul style={{ height: 300, overflowY: "auto" }}>
      {map(
        cards,
        ({
          id,
          name,
          username,
          email,
          address: {
            street,
            suite,
            city,
            zipcode,
            geo: { lat, lng }
          }
        }) => (
          <li key={id}>
            <strong>id:</strong> {id}
            <ul>
              <li>
                <strong>Username:</strong> {username}
              </li>
              <li>
                <strong>Name:</strong> {name}
              </li>
              <li>
                <strong>Email:</strong> {email}
              </li>
              <li>
                <strong>Street: </strong>
                {street}
              </li>
              <li>
                <strong>Suite: </strong>
                {suite}
              </li>
              <li>
                <strong>City: </strong>
                {city}
              </li>
              <li>
                <strong>Zipcode: </strong>
                {zipcode}
              </li>
              <li>
                <strong>Lat: </strong>
                {lat}
              </li>
              <li>
                <strong>Lng: </strong>
                {lng}
              </li>
            </ul>
          </li>
        )
      )}
    </ul>
  </Fragment>
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52346970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档