首页 > 解决方案 > 如何在 React 中使用 JSON 数据

问题描述

我不明白如何在 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})。如果您打算渲染一组子项,请改用数组。

截屏

标签: jsonreactjsaxios

解决方案


// 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>

I think the problem is that you're trying to render the object instead of rendering each of the fields. Since I don't see your full App component implementation, I'll give you the best answer I can.

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} />);
}

You are probably getting that error because you can't render the whole object, but instead, you have to render each field.

Your fetching logic however looks correct!


推荐阅读