Reactjs中的setState不是函数
我是新来的反应,我试图使用 APIfetch和setState状态变量命中 API ,但它抛出错误为
Unhandled Rejection (TypeError): Object(...) is not a function
这是代码-> CodeSandboxLink
import React from "react";
import { useState, useEffect, setState } from "react";
import "./styles.css";
export default function App() {
const [person, setPerson] = useState([]);
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => {
return response.json();
})
.then((data) => {
setState(data);
});
console.log("dasdasd", person);
return <div className="App">{JSON.stringify(person)}</div>;
}
请建议我哪里做错了。
回答
import React from "react";
import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [person, setPerson] = useState([]);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => {
return response.json();
})
.then((data) => {
setPerson(data); // You Need this For set Person to `state person`
});
}, []);
console.log("dasdasd", person);
return <div className="App">{JSON.stringify(person)}</div>;
}
API 使用状态:https ://reactjs.org/docs/hooks-state.html
API 使用效果:https ://reactjs.org/docs/hooks-effect.html
- You've put the fetch code in the body of your component, so it's happening on every render. When do you want to fetch? If it's when the component mounts, put it in a useEffect