首页 > 解决方案 > 地图不是反应中的功能

问题描述

我已经尝试了三天来解决我不能把几个元素放在一个数组中,但是如果我只能放一个当我放入 returnthis.state.dat.nombre或者dat.carrera它可以工作,但是如果我尝试使用 map 函数我做得不到

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dat: [],
      isFetch: true
    };
  }

  componentDidMount() {
    var url =
      "https://cors-anywhere.herokuapp.com/http://sipla.cuci.udg.mx/sc/horariop.php?c=219359735&k=0d8ce4fab5f4df9ce711cae81e044e1a";

    fetch(url, {
      method: "GET",
      headers: {
        "X-Requested-With": "XMLHttpRequest"
      }
    })
      .then(response => {
        return response.json();
      })
      .then(art => {
        this.setState({ dat: art, isFetch: false });
      });
  }

  render() {
    if (this.state.isFetch) {
      return "cargando....";
    }

    this.state.dat.map(art => {
      return (
        <tr key={art.codigo}>
          <td>{art.nombre}</td>
          <td>{art.carrera}</td>
          <td>{art.horarios}</td>
        </tr>
      );
    });
  }
}

export default App;

错误

标签: javascriptreactjsmeteor

解决方案


当我检查你的 API 时,我得到了这些数据

{
    carrera: "INGENIERIA EN COMPUTACION"
    ciclo_ingreso: "2019A"
    clave_carrera: "INCO"
    codigo: "219359735"
    cu: "CENTRO UNIVERSITARIO DE LA CIENEGA"
    estatus: "ACTIVO"
    fecha_consulta: "2019-07-12 12:20:20"
    horarios: (4) [{…}, {…}, {…}, {…}]
    nivel: "LICENCIATURA"
    nombre: "MARIA CECILIA PEREZ PEREZ"
    sede: "CAMPUS OCOTLAN"
    ultimo_ciclo: "2019B"
}

这不是数组。map数组的函数。

如果你想使用这些数据,你可以这样写。

render() {

    if(this.state.isFetch){
        return 'cargando....'
    }
    const {dat} = this.state;
    return (
        <tr key={dat.codigo}>
          <td>{dat.nombre}</td>
          <td>{dat.carrera}</td>
          <td>{dat.horarios}</td>
        </tr>
     );
}

推荐阅读