首页 > 解决方案 > 当我将数据置于状态时无法获取 json 中的数组

问题描述

我无法以 JSON 格式获取数组数据。我使用 node.js 发送 json 文件,代码在下面。

const express = require("express");
const router = express.Router(); // 라우터 분리

router.get("/api/hello", (req, res) => {
  // app 대신 router에 연결
  res.json({ express: "hello~" });
});

router.get("/api/beef", (req, res) => {
  res.json();
});

module.exports = router; // 모듈로 만드는 부분

我用json发送的数据是这样的。

  {
    "test": "Beef data get Completed",
    "name": "beef",
    "data": [
      { "productName": "양지", "price": 20000 },
      { "productName": "갈비", "price": 30000 },
      { "productName": "등심", "price": 15000 }
    ]
  }
]

然后我使用 fetch 获取数据,并将其保存在state中。我在 fetch 函数中获得了我想要的正确数据,但是当我尝试从 fetch 函数中获取数据时,我不断收到错误消息,例如无法获取属性 blahblahblah ... 这是我在客户端中执行的代码。

import React, { Component } from "react";

const itemList = ["돼지고기", "소고기", "닭&오리", "Sale", "연락처"];

class Contents extends Component {
  state = {
    parsedJson : "",
  };

  componentDidMount() {
    this._callAPI()
      .then(parsedJson=>{
        console.log("In the fetch : ",parsedJson[0].data[0])
        this.setState({
          parsedJson
        })
      })
      .catch(error => {
        console.log(error);
        this.setState({
          ...this.state,
          isError: true
        });
      });
  }

  _callAPI = async () => {
    const response = await fetch(`api/${this.props.curPage}`);
    const data = response.json();
    if (response.status !== 200) throw Error(data.message);

    return data;
  };

  render() {
    const stateData = this.state;
    console.log("In the render : ",stateData.parsedJson[0].data[0]) <- !!!!!!!!!!!! where error occur
    return (
      <>
        <RenderByItemList
          curPage={this.props.curPage}
          data={stateData.productData}
        />
      </>
    );
  }
}

标签: node.jsjsonreactjs

解决方案


在您的组件的第一次渲染中,parsedJson是字符串,并且stateData.parsedJson[0]返回一个空字符串,并且空字符串上没有data属性,因此您会收到错误消息。

为了解决这个问题,你必须在你的渲染方法中写一个 if :

import React, { Component } from "react";

const itemList = ["돼지고기", "소고기", "닭&amp;오리", "Sale", "연락처"];

class Contents extends Component {
  state = {
    parsedJson: [],
    error: null,
  };

  componentDidMount() {
    this._callAPI()
      .then(res => {
        this.setState({
          parsedJson: res[0].data, // here we set state the data array
        })
      })
      .catch(error => {
        console.log(error);
        this.setState({
          ...this.state,
          error // here we set state occurred error
        });
      });
  }

  _callAPI = async () => {
    const response = await fetch(`api/${this.props.curPage}`);
    const data = response.json();
    if (response.status !== 200) throw Error(data.message);

    return data;
  };

  render() {
    const { parsedJson, error } = this.state;

    if (parsedJson && parsedJson.length) {
      return <RenderByItemList
        curPage={this.props.curPage}
        data={parsedJson}
      />
    } else {
      return !!error || 'loading';
    }
  }
}

而且最好处理 fetch 操作的加载:

import React, { Component } from "react";

const itemList = ["돼지고기", "소고기", "닭&amp;오리", "Sale", "연락처"];

class Contents extends Component {
  state = {
    parsedJson: [],
    error: null,
    loading: false
  };

  componentDidMount() {
    this.setState({
      loading: true,
    }, () => {
      this._callAPI()
        .then(res => {
          this.setState({
            parsedJson: res[0].data, // here we set state the data array
            loading: false,
            error: null,
          })
        })
        .catch(error => {
          console.log(error);
          this.setState({
            loading: false,
            error // here we set state occurred error
          });
        });
    })
  }

  _callAPI = async () => {
    const response = await fetch(`api/${this.props.curPage}`);
    const data = response.json();
    if (response.status !== 200) throw Error(data.message);

    return data;
  };

  render() {
    const { parsedJson, error, loading } = this.state;

    if (loading) {
      return 'loading' // or write a Loading component and render it everywhere
    } else if (error) {
      return error // or write an Error component
    } else {
      return (
        <RenderByItemList
          curPage={this.props.curPage}
          data={parsedJson}
        />
      );
    }
  }
}


推荐阅读