从获取而不是静态数据的加载数据无法正常工作
我有一些代码试图获取一些数据并将其保存以更新列表数组,但没有对其进行更新。下面的代码是一些硬编码的数组,可以正常工作,但是在第二个我尝试获取数据但没有什么?
任何想知道我出错的地方,我都不会真正掌握这一点。感谢
有效的代码: -
const data = [
{id: '1', name: 'A'},
{id: '2', name: 'B'},
{id: '3', name: 'C'},
{id: '4', name: 'D'},
{id: '5', name: 'E'}
];
export default function App() {
const [lists, setLists] = useState(data);
我想用来获取什么:
export default function App() {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
const [lists, setLists] = useState('');
const getData = () =>
fetch(fetchURL)
.then((res) => res.json());
useEffect(() => {
getData().then((lists) => setLists(res.data) // If I use data it can display the hard coded array //
}, []);
我在做什么错?
I have a bit of code that is trying to fetch some data and save it to update a list array but is is not updating it. The code below is some hard coded array that works fine but in the second I try to fetch the data but nothing?
Any idea where I am going wrong, I am not really getting the hang of this. Thanks
The code which works :-
const data = [
{id: '1', name: 'A'},
{id: '2', name: 'B'},
{id: '3', name: 'C'},
{id: '4', name: 'D'},
{id: '5', name: 'E'}
];
export default function App() {
const [lists, setLists] = useState(data);
And what I am trying to use to fetch :
export default function App() {
const fetchURL = 'https://www.uberfantasies.com/rn.php'
const [lists, setLists] = useState('');
const getData = () =>
fetch(fetchURL)
.then((res) => res.json());
useEffect(() => {
getData().then((lists) => setLists(res.data) // If I use data it can display the hard coded array //
}, []);
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这将加载数据一次并在组件安装时更新列表
This will load the data once and update the list when the component mounts
您可以记录getData函数的响应,而不是将其设置为状态吗?您还可以将功能重构为这样的东西吗?
另外,在使用效果函数中,该
res
变量来自哪里?我认为应该是列表
。Can you log the response of your getData function instead of setting it to state? Also can you refactor your function to something like this pls.
Also, in the useEffect function, where did that
res
variable come from? I assume it should belists
.