首页 > 解决方案 > 我有一个 fetch ReactJS 的问题,我无法在组件安装或函数中获取数据

问题描述

我想从我的状态的电影数据库中获取数据,我尝试使用我做不到的钩子,现在与状态相同的问题。

     componentDidMount() {

   fetch(jsonUrl)
      .then(response => {
        response.json();
      })
      .then( data => {
        console.log("CDM", data);
      });
  }

当我尝试在 ComponentDidMount 内部或函数内部或 useEffect Hooks 内部进行获取时,它不会返回任何内容,只会返回未定义的内容。

我要数据,请帮帮我。

非常感谢

标签: reactjsfunctionreact-hooksfetch

解决方案


我看到了回调问题

.then(response => {
     response.json(); 
     // No explicit return then this function will return undefined
})

它应该是

.then(response => {
     return response.json(); // this returns whatever returned from response.json()
})

或者

.then(response => response.json())

推荐阅读