我正在构建一个小型应用程序。目前,我一直试图显示后端给出的响应。
我一直在使用this guide来实现数据获取挂钩,除了尝试在列表中显示返回的条目外,其他所有方法都有效。
这是我在组件中的代码的样子:
import React, { Fragment, useState, useEffect } from "react";
import axios from 'axios';
function Search() {
const [zone, setZone] = useState('');
const [results, setResults] = useState({entries: []});
const [url, setUrl] = useState(
`http://localhost:4000/entries/view/`
);
useEffect(() => {
const fetchEntries = async () => {
const result = await axios.get(url);
setResults({entries: result.entries});
};
fetchEntries();
}, [url]);
return (
<Fragment>
<input type="text" value={zone} onChange={e => setZone(e.target.value)} />
<button type="btn-primary" onClick={() =>
setUrl(`http://localhost:4000/entries/view/${zone}`)
}>
Search
</button>
<ul>
{results.entries.map(item => (
<li key={item._id}>
<div>{item.entry_description}</div>
</li>
))}
</ul>
</Fragment>
);
}
export default Search;
以下是API响应的示例:
{
"entries": [
{
"_id": "5d365d9af8b0625f345a8cea",
"entry_description": "Test ui",
"entry_time": "Now",
"entry_author": "Me",
"entry_zone": "12345",
"__v": 0
},
{
"_id": "5d367e3bbd8b13188c0d638b",
"entry_description": "Test still?",
"entry_time": "Now",
"entry_author": "Me",
"entry_zone": "12345",
"__v": 0
}
]
}
我收到的当前错误消息是:
The above error occurred in the <Search> component:
in Search (created by Context.Consumer)
in Route (at App.js:21)
in div (at App.js:14)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:13)
in App (at src/index.js:7)
Consider adding an error boundary to your tree to customize error handling behavior.
TypeError: results.entries is undefined
home.component.js:30
TypeError: results.entries is undefined
home.component.js:30
我非常感谢您提供任何帮助找出导致此问题的原因。
答案 0 :(得分:1)
您似乎将api结果包装在一个数组中,而您只需要将其分配给Enteries
useEffect(() => {
const fetchEntries = async () => {
const result = await axios.get(url);
setResults({entries: result.entries});
};
fetchEntries();
}, [url]);
答案 1 :(得分:0)
我认为问题是您将数组放入数组中。 [result.entries]
setResults({entries: [result.entries]});
应该是
setResults({entries: result.entries});
答案 2 :(得分:0)
因此,尽管我不太了解它,但我现在已经开始使用它了。我使用this code并更改了一些名称以使其与变量名一起使用。我认为此修复与这段代码中的useEffect()依赖关系有关,包括查询变量。在我的原始代码中,我将它们组合到一个url中,然后在依赖项中也没有包含zone变量。
这是我的最终代码:
{% for g in users %}
<td>{{ g.username }}</td>>
<td>{{ g.scrumygoals.goal_name }}</td>>
<td>{{ g.scrumygoals.goal_id }}</td>>
{% endfor %}