开发者问题收集

如何从 React js 中的 api 访问对象数组?

2020-12-21
1424

我正在尝试在 React js 中映射对象数组,我必须做两件事,一是我必须根据输入类型显示字段,二是我必须映射来自 API 的数据,问题是每当我尝试在我的组件中映射数据时,它都会一直给我一个错误,即 Uncaught TypeError: Cannot read property 'map' of undefined 我被卡住了,无法摆脱它 您可以在此处看到来自 API 的响应

我的组件

import React, { Component } from "react";
import {
  FormCardComponent,
  TextInputComponent,
  RadioInputComponent,
  SelectComponent,
} from "../../components/index";
import IntlMessages from "../../common/constants/IntlMessages";
import { TopBar } from "../../layouts/authLayout/components/index";
import { getEmsForms } from "../../redux/action/categories";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";

class DummyForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      field: "",
      checkBox: "",
      options: "",
      radioField: "",
      error: "",
    };
  }
  componentDidMount() {
    this.props.getEmsForms();
  }

  render() {
    console.log("COMP", JSON.stringify(this.props.getForms.data));
    return (
      <React.Fragment>
        <div className="col" style={{ marginTop: "50px" }}>
          <React.Fragment>
//here iam maping the data
            {this.props.getForms.data.map((item) => {
              <TextInputComponent
                style={{ marginTop: "50px" }}
                label={item.fieldName}
                type="text"
                placeholder={"Abdul"}
                value={this.state.name}
                onChange={(e) =>
                  this.setState({ name: e.target.value, error: "" })
                }
              />;
            })}
            <select
              className="custom-select"
              id="inputGroupSelect01"
              style={{ marginTop: "50px" }}
            >
              <option>yes</option>
              <option>yes</option>
            </select>
            <div style={{ marginTop: "50px" }}>
              <SelectComponent
                style={{ marginTop: "50px" }}
                name={"select2"}
                value={this.state.select2}
                label={
                  "Jeg vil gerne modtage en SMS når der er nyheder til mig"
                }
                onChange={(e) => this.setState({ select2: e.target.checked })}
              />
              <SelectComponent
                style={{ marginTop: "50px" }}
                name={"select2"}
                value={this.state.select2}
                label={
                  "Jeg vil gerne modtage en SMS når der er nyheder til mig"
                }
                onChange={(e) => this.setState({ select2: e.target.checked })}
              />
              <SelectComponent
                style={{ marginTop: "50px" }}
                name={"select2"}
                value={this.state.select2}
                label={
                  "Jeg vil gerne modtage en SMS når der er nyheder til mig"
                }
                onChange={(e) => this.setState({ select2: e.target.checked })}
              />
              <SelectComponent
                style={{ marginTop: "50px" }}
                name={"select2"}
                value={this.state.select2}
                label={
                  "Jeg vil gerne modtage en SMS når der er nyheder til mig"
                }
                onChange={(e) => this.setState({ select2: e.target.checked })}
              />
            </div>
            <div style={{ marginTop: "50px" }}>
              <RadioInputComponent
                title="gender"
                value={this.state.gender}
                name={["male", "female", "other"]}
                onChange={(e) => {
                  this.setState({ gender: e.target.value, error: "" });
                }}
              />
            </div>
            <div className="row" style={{ marginTop: "50px" }}>
              <div className="col d-flex justify-content-start">
                <button className="btn-danger" onClick={this.toggleModal}>
                  Ja
                </button>
              </div>
              <div className="col d-flex justify-content-end">
                <button className="btn btn-success button-margin">Ja</button>
              </div>
            </div>
          </React.Fragment>
        </div>
      </React.Fragment>
    );
  }
}
const mapStateToProps = (data) => ({
  getForms: data.categories.forms,
});

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(
    {
      getEmsForms,
    },
    dispatch
  );

export default connect(mapStateToProps, mapDispatchToProps)(DummyForm);

我的 API 响应

[
    {
        "question_id": 4,
        "fieldName": "LastName",
        "order": 0,
        "isRequired": true,
        "isShown": true,
        "isEditable": false,
        "fieldLabelText": "First Name da",
        "errorText": "First Name Error da",
        "inputType": "textbox",
        "inputOptions": [],
        "inputOptionsCustom": []
    },
    {
        "question_id": 3,
        "fieldName": "FirstName",
        "order": 1,
        "isRequired": true,
        "isShown": true,
        "isEditable": false,
        "fieldLabelText": "First Name da",
        "errorText": "First Name Error da",
        "inputType": "textbox",
        "inputOptions": [],
        "inputOptionsCustom": []
    },
    {
        "question_id": 2,
        "fieldName": "Age",
        "order": 2,
        "isRequired": true,
        "isShown": true,
        "isEditable": false,
        "fieldLabelText": "First Name da",
        "errorText": "First Name Error da",
        "inputType": "dropdown",
        "inputOptions": [
            {
                "option_id": 7,
                "text": "18",
                "value": "18"
            },
            {
                "option_id": 8,
                "text": "19",
                "value": "19"
            },
            {
                "option_id": 9,
                "text": "20",
                "value": "20"
            },
            {
                "option_id": 10,
                "text": "21",
                "value": "21"
            },
            {
                "option_id": 11,
                "text": "22",
                "value": "22"
            },
            {
                "option_id": 12,
                "text": "23",
                "value": "23"
            }
        ],
        "inputOptionsCustom": []
    },
    {
        "question_id": 5,
        "fieldName": "PhoneNumber",
        "order": 3,
        "isRequired": false,
        "isShown": true,
        "isEditable": false,
        "fieldLabelText": "First Name da",
        "errorText": "First Name Error da",
        "inputType": "textbox",
        "inputOptions": [],
        "inputOptionsCustom": []
    }
]
2个回答

也许你可以尝试这样做:

{this.props.getForms.data?this.props.getForms.data.map((item) => {
              <TextInputComponent
                style={{ marginTop: "50px" }}
                label={item.fieldName}
                type="text"
                placeholder={"Abdul"}
                value={this.state.name}
                onChange={(e) =>
                  this.setState({ name: e.target.value, error: "" })
                }
              />;
            }):''}
Sakshi
2020-12-21

数据最初可能未定义,因此在映射之前请检查它是否存在。

例如

this.props.getForms.data && this.props.getForms.data.map(item=>{
//render
})
Adithya
2020-12-21