如何使用useEffect渲染数组对象

时间:2019-09-13 22:39:44

标签: reactjs

我似乎无法使数组对象正常工作。我想将数组从api传递到setstate函数,以将该状态转换为数组。然后遍历该数组。迭代应该使我可以访问对象的属性。我想访问唯一的对象属性以返回并将它们渲染到我的组件中。但是,出现错误“期望的对象”。

<!DOCTYPE html>
<html>
    <meta charset="utf-8" />
    ...

1 个答案:

答案 0 :(得分:0)

这很奇怪,在此沙箱中似乎工作正常:https://codesandbox.io/s/lingering-brook-veo3f

我也将状态初始化为一个空数组:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import CharacterComponent from "./CharacterComponent";

import "./styles.css";

function App() {
  const [character, setCharacter] = useState([]);
  useEffect(() => {
    axios
      .get("https://swapi.co/api/people")
      .then(res => setCharacter(res.data.results));
  }, []);

  return (
    <div className="App">
      {character.map(item => (
        <CharacterComponent id={item} />
      ))}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

也许看看您的子组件是否有问题:

import React from "react";

const CharacterComponent = ({ id }) => {
  return <div>{id.name}</div>;
};

export default CharacterComponent;