我似乎不能让我的数组对象工作。我希望将api中的数组传递给setstate函数,以便将状态转换为数组。然后遍历该数组。迭代应该可以让我访问对象的属性。我想要访问唯一的对象属性以返回并将它们呈现到我的组件中。然而,我得到了一个错误"Object Expected“。
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>
</>
)
}发布于 2019-09-14 06:53:12
这很奇怪,似乎在这个沙箱中工作得很好: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;https://stackoverflow.com/questions/57931064
复制相似问题