reactjs - 无法从后端使用 React.js 设置数据
问题描述
{数据:数组(15)}
data[0]:
option: Array(1)
0: "String"
_id: "String"
col1: "String"
col2: "String"
col3: "String"
....数据[14]
这是前端代码:
const Component1 = () => {
const [dbvalue, setDbvalue] = useState(null)
//option, _id, col1, col2, col3
const getAlldbValue = async () => {
try {
const resp = await services.getAlldbValue();
console.log(resp) //enter F12 can get total data from back end.
setDbvalue(resp.data.data)
console.log(dbvalue) //setDbvalue() not work , this print null
} catch (error) {
console.log(error)
alert('Failed!')
}
}
useEffect(() => {
getAlldbValue()
}, [])
if(!dbvalue) {
return (
<p>Loading Component...</p> //not appear
)
}
return (
<p>{dbvalue}</p> //not appear
);
};
export default Component1;
如何将此嵌套对象 json 设置到此 dbvalue 中?我想使用 dbvalue.keyname 来显示。谢谢你的帮助
解决方案
首先,您的 console.log 打印 null 因为当您使用 setState 时,您刚刚设置的变量只会在下一次渲染中设置。尝试打印resp.data.data
而不是放在函数console.log(dbvalue)
之外getAlldbValue
,这样您可以更好地理解。
还,
`return (
<p>{dbvalue}</p> //not appear
);`
您尝试将对象放入 HTML 元素中,尝试dbvalue[0].col1
或您想要显示的任何内容。
希望它可以帮助你。
推荐阅读
- python - 无法使用文本值更新字幕字符串
- javascript - 注释不显示在 vue-chartjs 中
- python - 检查列表中是否至少有一个以特定字符开头的元素
- sql - Oracle:当 IN 子句没有输入时选择所有值的 SQL 查询
- flutter - 如何从 Scaffold 重构/提取底部导航栏?
- c# - 从 .NET Core 1 升级到 .NET 5 的 DbContext 问题
- ansible - 如何在 AWX extra-var 上正确转义双引号
- wrapper - 在gym中,我们应该如何实现环境的render方法,让Monitor产生的视频不黑?
- jsf - 在 JSF 中使用不同的输入值方法重用表单
- lua - 你如何做一个“范围”?在 Lua 中