【问题标题】:setState in Reactjs is not a functionReactjs 中的 setState 不是函数
【发布时间】:2020-12-22 17:06:24
【问题描述】:

我是新手,我正在尝试使用fetchsetState 访问一个状态变量的 API,但它会抛出错误

Unhandled Rejection (TypeError): Object(...) is not a function

Here is the code -> 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>;
}

请提出我做错的地方。

【问题讨论】:

  • 您将变量命名为 setPerson,而不是 setState。致电setPerson(data)
  • 你应该在问题中发布代码......不是链接
  • @NicholasTower,你能再刷新一下链接吗?

标签: javascript reactjs react-hooks fetch setstate


【解决方案1】:
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

【讨论】:

  • 当我使用setPerson 时,它反复点击API 并且从未停止。这是工作演示链接codesandbox.io/s/laughing-ramanujan-1ltcw?file=/src/App.js
  • @Mahesh 在reactjs.org/docs/hooks-effect.html中包装你的api调用
  • 您已将获取代码放在组件的主体中,因此每次渲染都会发生这种情况。你想什么时候取?如果是在组件挂载的时候,把它放在一个useEffect中
  • 您应该在useEffect 中使用fetch(类似于componentDidMountcomponentDidUpdate
  • 有什么区别?您仍然需要等待响应(显示加载指示器或其他内容)。
猜你喜欢
  • 2021-06-01
  • 2017-04-24
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
相关资源
最近更新 更多