首页 > 解决方案 > 如何从反应组件访问数组中的数组?

问题描述

我有这个数组:

{
  "firstname": "Jessica",
  "lastname": "Wood",
  "favorite": {
        "movie": Flint Town,
        "drink": Sprite
  }
}

我正在尝试喝酒,但发现对象无效,因为发现 React 孩子:带钥匙的对象。

我该如何解决?

我的反应组件:

import React, { Component } from 'react';
import axios from 'axios';

class Home extends Component {

  state = {
    info: []
  }

  componentDidMount() {
    axios.get('http://localhost:9000/api')
      .then(res => {
        const info = res.data;
        this.setState({ info });
      })
  }

  render() {
    return (
      <ul>
        <li>{this.state.info.favorite.drink}</li>
      </ul>
    )
  }
}
export default Home;

标签: javascriptarraysnode.jsjsonreactjs

解决方案


您需要解析“最喜欢的”对象中的值,以便它们可以呈现为字符串。

看起来您还试图在道具this.state.info存在之前访问它。这就是为什么它给你未定义的错误。render 方法在您将任何内容分配给 info 之前运行,您在 componentDidMount() 中执行了此操作。

要解决此问题,我们可以使用 loading-state 值来确定要显示的内容。加载状态将在您的 componentDidMount() 逻辑完成后切换,确保您的状态已填充。

这是沙箱:https ://codesandbox.io/s/bold-germain-k3f23

class Home extends Component {
  state = {
    info: {},
    loading: true
  };

  componentDidMount() {
    axios.get("http://localhost:9000//").then(res => {
      const info = res.data;
      const parsedInfo = {
        ...info,
        favorite: Object.entries(info.favorite).reduce((obj, [k, v]) => {
          obj[k] = "" + v;
          return obj;
        }, {})
      };

      this.setState({ info: parsedInfo, loading: false });
    });
  }

  render() {
    const { loading, info } = this.state;
    if (loading) {
      return <div>Loading</div>;
    } else {
      return (
        <div>
          <div>{info.favorite.movie}</div>
          <div>{info.favorite.drink}</div>
        </div>
      );
    }
  }
}

推荐阅读