简体   繁体   中英

Uncaught TypeError: data.map is not a function on reactjs dummy component

I am trying to render some basic values from an array of strings into a dummy react component. but I get this error:

在此处输入图片说明

The code is this:

import React, { Component } from 'react';

import { Row, Col } from 'antd';
import PageHeader from '../../components/utility/pageHeader';
import Box from '../../components/utility/box';
import LayoutWrapper from '../../components/utility/layoutWrapper.js';
import ContentHolder from '../../components/utility/contentHolder';
import basicStyle from '../../settings/basicStyle';
import IntlMessages from '../../components/utility/intlMessages';
import { adalApiFetch } from '../../adalConfig';

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: []
    };

  }

  getValues() {
    adalApiFetch(fetch, '/values', {})
      .then((response) => {

        // This is where you deal with your API response. In this case, we            
        // interpret the response as JSON, and then call `setState` with the
        // pretty-printed JSON-stringified object.
        response.json()
          .then((responseJson) => {
            this.setState({ data: JSON.stringify(responseJson, null, 2) })
          });
      })
      .catch((error) => {

        // Don't forget to handle errors!
        console.error(error);
      })

  }

  fetchData() {
    try {
        const data =  this.getValues();
        !this.isCancelled && this.setState({ data });
    } catch(error) {
        console.log(error);
    }
  }

  componentDidMount(){
    this.fetchData();
  }

  render() {
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;
    const radioStyle = {
        display: 'block',
        height: '30px',
        lineHeight: '30px'
      };
      const plainOptions = ['Apple', 'Pear', 'Orange'];
      const options = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange' }
      ];
      const optionsWithDisabled = [
        { label: 'Apple', value: 'Apple' },
        { label: 'Pear', value: 'Pear' },
        { label: 'Orange', value: 'Orange', disabled: false }
      ];

    return (
      <div>
        <LayoutWrapper>
        <PageHeader>{<IntlMessages id="pageTitles.TenantAdministration" />}</PageHeader>
        <Row style={rowStyle} gutter={gutter} justify="start">
          <Col md={12} sm={12} xs={24} style={colStyle}>
            <Box
              title={<IntlMessages id="pageTitles.TenantAdministration" />}
              subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
            >
              <ContentHolder>
                  <ul>
                    {data && data.map(item => (
                        <li>{item.name}</li>
                    ))}
                  </ul>
              </ContentHolder>
            </Box>
          </Col>
        </Row>
      </LayoutWrapper>
      </div>
    );
  }
}

You get your error because you are trying to use the array method map on a string. You should not stringify the response with JSON.stringify , since that will make your data into a string.

The try/catch and const data = this.getValues() in fetchData will not work either since getValues would be asynchronous, if you would have returned the promise.

Example

class App extends Component {
  state = {
    data: []
  };

  fetchData = () => {
    adalApiFetch(fetch, "/values", {})
      .then(response => response.json())
      .then(responseJson => {
        if (!this.isCancelled) {
          this.setState({ data: responseJson });
        }
      })
      .catch(error => {
        console.error(error);
      });
  };

  componentDidMount() {
    this.fetchData();
  }

  render() {
    const { data } = this.state;
    const { rowStyle, colStyle, gutter } = basicStyle;
    const radioStyle = {
      display: "block",
      height: "30px",
      lineHeight: "30px"
    };
    const plainOptions = ["Apple", "Pear", "Orange"];
    const options = [
      { label: "Apple", value: "Apple" },
      { label: "Pear", value: "Pear" },
      { label: "Orange", value: "Orange" }
    ];
    const optionsWithDisabled = [
      { label: "Apple", value: "Apple" },
      { label: "Pear", value: "Pear" },
      { label: "Orange", value: "Orange", disabled: false }
    ];

    return (
      <div>
        <LayoutWrapper>
          <PageHeader>
            {<IntlMessages id="pageTitles.TenantAdministration" />}
          </PageHeader>
          <Row style={rowStyle} gutter={gutter} justify="start">
            <Col md={12} sm={12} xs={24} style={colStyle}>
              <Box
                title={<IntlMessages id="pageTitles.TenantAdministration" />}
                subtitle={<IntlMessages id="pageTitles.TenantAdministration" />}
              >
                <ContentHolder>
                  <ul>{data.map(item => <li>{item.name}</li>)}</ul>
                </ContentHolder>
              </Box>
            </Col>
          </Row>
        </LayoutWrapper>
      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM