json - 如何在 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})。如果您打算渲染一组子项,请改用数组。
解决方案
// 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!
推荐阅读
- swift - 通过点击 Mapkit 中的 Annotation 触发 NavigationLink
- node.js - Sequelize:使用源中的多个键来包含目标模型
- r - 将数据集转换为在 R 中结合列和行的整洁格式
- powershell - 如何在控制台中关闭语法突出显示?视窗 10 2020
- tensorflow - keras tensorflow metric 总是计算损失
- javascript - Vuejs javascript模块导入“TypeError:不是构造函数”
- r - 条形图中正负条的不同条颜色
- sql - SQL Server - 使用内部查询自联接更新值的代码
- reactjs - 历史和路由器不适用于电子
- r - 在ggplot中绘制多个变量的趋势线和方程