如果箭头函数返回一个函数,但当它为 useEffect 返回 null 时则不会出错

问题描述 投票:0回答:1

这是我的文章组件中的代码片段:

const [articles, setArticles] = useState([]);
  const [err, setErr] = useState("");

  const token = sessionStorage.getItem("token");
  const axiosWithToken = axios.create({
    headers: { Authorization: `Bearer ${token}` },
  });

  const getArticles = async () => {
    const res = await axiosWithToken.get("http://localhost:5000/user/articles");

    if (res.data.message === "All Articles") {
      setArticles(res.data.payload);
    } else {
      setErr(res.data.message);
    }
  };

  useEffect(() => {
    getArticles();
  }, []);

此代码运行没有任何错误。但我认为仅运行一个函数就使用带大括号的箭头函数太多了,所以我将 useEffect 挂钩中的箭头函数更改为:

useEffect(() => getArticles(), []);

但是现在,当我加载文章组件并转到任何其他路由时,页面会抛出一个未知错误,该错误仅表明

'n' is not a function
。我不明白为什么会发生这种情况,因为我认为它们在功能上是相同的。

javascript reactjs react-hooks react-router
1个回答
0
投票

问题是,通过更改为简写形式,您已经隐式添加了

return
。您的速记版本与
{}
的版本不同;相反,它相当于:

useEffect(() => {
    return getArticles();
//  ^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
}, []);

useEffect
期望如果您给它的回调返回除
undefined
(或可能是
null
)以外的任何内容,则 React 应该在卸载时或重新运行效果之前使用它的清理函数。你的
getArticles
函数返回一个承诺(就像所有
async
函数一样),React 试图将其用作清理函数。

所以你可能想保留这些

{}
而不是删除它们。

© www.soinside.com 2019 - 2024. All rights reserved.