【问题标题】:Cannot get the array in json when I put the data in the state当我将数据置于状态时无法获取 json 中的数组
【发布时间】:2020-06-12 03:11:30
【问题描述】:

我无法以 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 函数中获取数据时,我不断收到错误消息,例如 cannot get the property 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.js json reactjs


    【解决方案1】:

    在你的组件第一次渲染时,parsedJson 是字符串,stateData.parsedJson[0] 返回一个空字符串,并且空字符串上没有data 属性,所以你得到了错误。

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

    import React, { Component } from "react";
    
    const itemList = ["돼지고기", "소고기", "닭&오리", "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 = ["돼지고기", "소고기", "닭&오리", "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}
            />
          );
        }
      }
    }
    
    

    【讨论】:

    • 那么你的意思是我不能在 componentDidMount 函数之外触摸数据数组?
    • 在做setState的时候可以摸一下。但是当您没有该属性时,您无法选择它,您将面临错误
    • 您还有问题吗?或者你通过了挑战?
    • 我通过了!!非常感谢~而我在评论中问的答案是这样的,我无法触摸setState函数之外的数据数组对吗?
    • 如果你手动改变状态,你会改变状态。所以如果你想改变任何改变 UI 的数据,你必须使用 setState 函数
    猜你喜欢
    • 2021-03-11
    • 2020-04-21
    • 2018-10-18
    • 1970-01-01
    • 2019-06-12
    • 2020-12-10
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多