【问题标题】:How to populate a div from the data from fetch如何从 fetch 的数据中填充 div
【发布时间】:2021-12-24 20:09:49
【问题描述】:

我在 this.state 的反应应用程序中获取我的输出,但我想把它带到外面并填充 div 以便我可以在前端显示它。我该怎么做?

 fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        console.log(state);
      })
      .catch((err) => {
        console.log(err);
      });

【问题讨论】:

  • 如果您共享遇到问题的完整组件,会更容易为您提供帮助。
  • 这能回答你的问题吗? stackoverflow.com/a/1533650

标签: javascript reactjs react-hooks


【解决方案1】:

你的例子有点不完整。无论如何,如果返回的数据是一个数组,我会这样做 https://codesandbox.io/s/mutable-leftpad-o3v30?file=/src/App.js

【讨论】:

  • 当我将 fetchData 传递给 h1 或 div 标签时,我收到此错误。 react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child (found: object with keys {result}). If you meant to render a collection of children, use an array instead.
  • 我附上了来自 console.log(data) @aetheode 的 API 输出的图片
  • 更新了代码沙盒上的代码 (codesandbox.io/s/mutable-leftpad-o3v30?file=/src/App.js)
【解决方案2】:

永远不要使用this.state 并直接赋值,因为它是不可变的, 你能做的是,

fetch("https://flask-api-test1.herokuapp.com/predict", {
  method: "post",
  body: formData,
})
  .then((res) => res.json())
  .then((result) => {
    this.setState({data:result});
    console.log(result);
  })
  .catch((err) => {
    console.log(err);
  });

【讨论】:

    【解决方案3】:

    如果你可以使用钩子,那么最简单的解决方案就是 useState

    import {useState} from 'react'  
    

    声明

    const [newState, setNewState] = useState()
    

    那你试试

     fetch("https://flask-api-test1.herokuapp.com/predict", {
          method: "post",
          body: formData,
        })
          .then((res) => res.json())
          .then((result) => {
            this.state = result;
            setNewState(state)
            console.log(state);
          })
          .catch((err) => {
            console.log(err);
          });
    

    你可以在 jsx 中为 div 使用现成的“newState”

    <div>
     {newState?.keyDataYouNeed}
    </div>
    

    【讨论】:

    • react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child (found: object with keys {result}). If you meant to render a collection of children, use an array instead. 我收到此错误
    • result: predictions: -3.5411367416381836 [[Prototype]]: Object [[Prototype]]: Object 这是我的 console.log(data) 输出
    • 为什么人们一直这样分配值,this.state = result; 大错特错,这样做,setNewState(result) 人,显然他没有使用反应钩子,
    • @AshishKamble 是的,我已经删除了this.state = result;我正在使用 useState
    • @harsh "Uncaught Error: Objects are not valid as a React child" 你得到这个错误是因为在“结果”中你有一个对象,并且 react 不能像控制台一样简单地显示它.log 如果您需要在控制台中查看,请尝试 console.log(JSON.stringify(newState.result)) 如果您需要从 JSX 中的结果中获取预测,请尝试 &lt;div&gt; {newState?.result?.predictions} &lt;/div&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2021-07-09
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多