首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用useEffect呈现数组对象

如何使用useEffect呈现数组对象
EN

Stack Overflow用户
提问于 2019-09-14 06:39:45
回答 1查看 3.7K关注 0票数 1

我似乎不能让我的数组对象工作。我希望将api中的数组传递给setstate函数,以便将状态转换为数组。然后遍历该数组。迭代应该可以让我访问对象的属性。我想要访问唯一的对象属性以返回并将它们呈现到我的组件中。然而,我得到了一个错误"Object Expected“。

代码语言:javascript
复制
import React,{useState,useEffect} from 'react';
import './App.css';
import { CharacterComponent } from "../src/CharacterComponent"
import axios from "axios"
import ReactDOM from "react-dom";

export const Characters = () => {
  // Try to think through what state you'll need for this app before starting. Then build out
  // the state properties here.

  // Fetch characters from the star wars api in an effect hook. Remember, anytime you have a 
  // side effect in a component, you want to think about which state and/or props it should
  // sync up with, if any.
  const [character,setCharacter] = useState({})
  useEffect( () => {
    axios.get("https://swapi.co/api/people")
    .then(res => setCharacter(res.data.results) )
  },[])

(console.log(character))
  return (
    <>
    <div>
    {character.map((element,index) => <CharacterComponent id={element} key={index} />)}
    </div>
    </>
  )


}
EN

回答 1

Stack Overflow用户

发布于 2019-09-14 06:53:12

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

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

代码语言:javascript
复制
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);

也许可以查看一下您的子组件是否有问题:

代码语言:javascript
复制
import React from "react";

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

export default CharacterComponent;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57931064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档