与componentDidMount类似的ReactJSUseMook行为

与componentDidMount类似的ReactJSUseMook行为,reactjs,react-hooks,Reactjs,React Hooks,我试图将useMemo类似的useEffect与componentDidMount行为一起使用,但我的useMemo的行为就像componentWillMount一样,并且呈现得势不可挡 代码如下: useMemo(() => { console.log('rendered'); fetch(`backend url`, { method: 'PUT', headers: { 'Content-Type': 'application/

我试图将useMemo类似的useEffect与componentDidMount行为一起使用,但我的useMemo的行为就像componentWillMount一样,并且呈现得势不可挡

代码如下:

useMemo(() => {
    console.log('rendered');
    fetch(`backend url`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userId: userInf._id,
        fields: ['readers', 'followers', 'news', 'podcast', 'video'],
      }),
    })
      .then((res) => res.json())
      .then((res) => {
        setUserArticles(res.news);
      })
      .catch((err) => err);
  }, [userArticles]);
有什么建议吗?

问题
usemo
钩子用于计算和记忆值。看起来您的钩子回调实际上正在更新某些状态,并且该状态或值也在钩子的依赖项数组中声明,该数组在更新和重新排序后,将再次运行钩子回调并更新状态。。。创建一个无限循环

解决方案 如果您希望在组件装载时仅发出一次副作用,如
componentDidMount
,则使用带有空依赖项数组的
useffect

useEffect(() => {
  console.log('rendered');
  fetch(`backend url`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      userId: userInf._id,
      fields: ['readers', 'followers', 'news', 'podcast', 'video'],
    }),
  })
    .then((res) => res.json())
    .then((res) => {
      setUserArticles(res.news);
    })
    .catch((err) => err);
}, []);

如果你想运行一个特效并且只清理一次(在安装和 卸载),您可以将空数组(
[]
)作为第二个参数传递。这 告诉React您的效果不依赖于道具的任何值 或状态,因此它永远不需要重新运行。这不是一个特殊的问题 案例-它直接从依赖项数组始终 工作

如果传递一个空数组(
[]
),则效果中的道具和状态 将始终具有其初始值。将
[]
作为第二个 参数更接近熟悉的
组件didmount
组件将卸载
心智模型,通常有更好的解决方案 避免过于频繁地重新运行效果。还有,别忘了这一点 延迟运行
useffect
,直到浏览器绘制完毕,这样做 额外的工作不是什么问题


[userArticles]
告诉它在每次
userArticles
更改时重新运行,并且由于钩子本身更改
userArticles
,它将触发重新运行。您可以尝试使用空数组,但据我所知,useMemo需要查看特定值以跟踪任何差异。我错了吗?只需使用
useffect
来发布诸如数据获取之类的副作用,这就是它的用途,
usemo
用于存储值。另外,您不能更新钩子依赖数组中的值,这将导致渲染循环。好的,谢谢@用户14587589取决于您想要的行为
usemo
还应该返回一个可以使用的值,否则最好使用
useffect