【问题标题】:How to use JSON data in React如何在 React 中使用 JSON 数据
【发布时间】:2021-05-29 00:45:14
【问题描述】:

我不明白如何在 React 中使用 JSON 数据。我的代码:

  function App() {
  const [image, setImage] = useState();
  const getImage = () => {
    axios.get('http://localhost:5000/api')
    .then(function (res) {
    setImage(res.data);
    })
   
  }

  useEffect(()=>{
    getImage()
  }, [])`

回复:

{
    "title": "this is a title",
    "description": "",
    "tags": "",
    "isSorted": false,
    "passed": false
}

错误信息:

错误:对象作为 React 子对象无效(找到:对象带有键 {title、description、tags、isSorted、passed})。如果您打算渲染一组子项,请改用数组。

【问题讨论】:

  • 将 console.log(res) 添加到您的 .then 回调函数中并在此处发布。很可能您正在尝试将对象而不是字符串分配给图像。
  • 您的渲染逻辑可能有问题...您是否尝试直接渲染 JSON 数据
  • 我知道我正在传递一个对象。我应该如何处理这个 json 对象?
  • 我使用 setImage() 将它传递给状态。是否不允许将对象传递给状态?
  • 没有 JSON。从axios 调用传递给then 函数的res 是一个对象。 JSON 是一种文本格式。这就是为什么你会收到关于对象不是有效的 React 子项的错误,而不是关于文本不是有效的 React 子项的错误。

标签: json reactjs axios


【解决方案1】:

// Get a hook function
const {useState, useEffect} = React;

const App = () => {
  const [images, setImages] = useState(0);
  
  useEffect(() => {
      setTimeout(() => {
         setImages({title: 'Foo', description: 'Bar...'});
      }, 1000);
  }, []);

  return images ? <p>{images.title}</p> : <p>Loading images...</p>;
};

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

我认为问题在于您尝试渲染对象而不是渲染每个字段。由于我没有看到您完整的 App 组件实现,因此我会尽力为您提供最佳答案。

function Image(props) {
   return ( 
     <>
       <h1>{props.title}</h1>
       <p>{props.descriptio</p>
     </>
   );
}

function App() {
  const [image, setImage] = useState();
  const getImage = () => {
    axios.get('http://localhost:5000/api')
    .then(function (res) {
    setImage(res.data);
    })
   
  }

  useEffect(()=>{
    getImage()
  }, [])

  // This is assuming how your App component SHOULD look
  return (<Image image={image} />);
}

您可能会收到该错误,因为您无法渲染整个对象,而是必须渲染每个字段。

但是您的获取逻辑看起来是正确的!

【讨论】:

  • 我应该把它包括在内,对不起。 return ( &lt;div className="App"&gt; &lt;header className="App-header"&gt; &lt;p&gt;{image}&lt;/p&gt; &lt;/header&gt; &lt;/div&gt;
  • 如果我尝试类似 {image.title) 它告诉我标题未定义。
  • 这是因为在初始渲染期间您的数据尚不可用,由于 useEffect(),您正在以异步方式获取数据。
  • 你要做的就是添加一个IF来查看数据是否可用。给我一秒钟,我正在为你创建一个你可以实现的工作示例:)
  • 好的,那我该怎么办?我只想将对象的值放入

    元素中。

猜你喜欢
  • 1970-01-01
  • 2021-03-25
  • 2023-02-07
  • 1970-01-01
  • 2020-05-05
  • 2016-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多