【问题标题】:React fetch data and set state accordingly doesn't work反应获取数据并相应地设置状态不起作用
【发布时间】:2022-07-29 02:51:33
【问题描述】:

在下面的代码中,settings 变量没有被设置。我确实在之后检查了console.log setSettings 并且我验证了使用该变量的组件正在接收默认的 {} 值。 fetch per se 是对的,我在浏览器的控制台中尝试过,我在 Network 选项卡中看到了 json。

我需要在第一次渲染时完成一次提取。

你能看一下吗?我在这上面花了很多时间,我想知道我做错了什么。谢谢!

    const [settings, setSettings] = React.useState({});

    function fetchSettings() {
        fetch("MYAPIENDPOINT/settings", {
            method: "GET",
            credentials: 'include',
            accept: 'application/json',
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw response;
        })
        .then((data) => {
            setSettings(data);
        })
        .catch(error => {console.log(error);});

    }

    React.useEffect(
        fetchSettings(),
        [settings]
    );

EDIT 使用settings 变量显示组件

    ...
    <div id="Grid" style={{ height: "700px" }}>
        {settings && <GenericGrid settings={settings} />}
    </div>

【问题讨论】:

  • 我没有看到setSettings(data) 调用有任何明显问题。我看到的唯一问题是使用settings 作为更新settings 状态的useEffect 挂钩的依赖项。这可能会导致渲染循环。 settings 在哪里使用而您没有看到它更新?
  • @DrewReese 感谢您的回复。我试图删除 settings 依赖项,但它仍然出错。我已更新问题以显示组件
  • 错误?!有什么错误?
  • useEffect(() => { fetchSettings(); }, []) 是正确的语法。 useEffect 接受 2 个参数:回调和依赖数组
  • 天哪,这是真的,shite @OktayYuzcan 谢谢!!!如果你写,我会在你的答案上打勾!谢谢老兄!

标签: reactjs react-hooks fetch use-effect


【解决方案1】:

useEffect 接受 2 个参数:回调和依赖数组。

正确的语法是:

useEffect(() => {
   function fetchSettings(){
      ...
   }

   fetchSettings();
}, []) 

如果您希望回调只触发一次,请将依赖项数组留空。 最好在回调中定义 fetchSettings 函数,这样它就不会在每次渲染时重新创建。

【讨论】:

    【解决方案2】:

    谢谢大家,我的应用陷入了严重的循环,一直在努力找出问题所在。你的 useEffect 语法解决了这个问题。我真的很感激。

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2020-01-24
      • 2017-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多