如何使用 useEffect setParams 并避免获得无限渲染? [英] How to setParams using useEffect and avoid getting infinty renderings?

查看:61
本文介绍了如何使用 useEffect setParams 并避免获得无限渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 react-navigation 并且我有一个动态标题,所以我正在使用 setParams 并将其放入标题中.

I'm using react-navigation and I have a dynamic header, so I'm using setParams and getting it in the title.

const MyComponent = ({navigation}) => {
    useEffect(() => {
        const { setParams, state } = navigation
        const { params = {} } = state
        const { description } = params
        setParams({ headerTitle: description })
    }, [])

    return (...)
}

MyComponent.navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('headerTitle')
})

这里的问题是我只想setParams一次(所以我使用[])但我收到一个警告(eslint(react-hooks/Exclusive-deps)) 并说我需要将 navigation 添加到依赖项数组.

The problem here is that I only want to setParams once (so I use []) but I get a warning (eslint(react-hooks/exhaustive-deps)) and says that I need to add navigation to the dependency array.

如果我在依赖数组中加入navigation,就会变成无限循环.

If I add navigation to the dependency array, it will become a infinty loop.

setParam updates => navigation call => setParam updates => navigation 并继续...

setParam updates => navigation call => setParam updates => navigation and continues...

如何只调用一次 setParam 并避免根据钩子的反应规则正确执行?

How can I call setParam only once and avoid do it correctly accordingly to react rule of hooks?

推荐答案

Could useRef 可以按照底部的建议解决这个问题 答案?

Could useRef solve this as suggested at the bottom this answer?

import React, { useRef, useEffect } from 'react';

const MyComponent = ({ navigation }) => {
  const { state } = navigation;
  const { params = {} } = state;
  const description = useRef(params.description);
  const setParams = useRef(navigation.setParams);

  useEffect(() => {
    setParams.current({ headerTitle: description.current });
  }, [description, setParams]);

  return (...);
}

MyComponent.navigationOptions = ({ navigation }) => ({
    title: navigation.getParam('headerTitle')
})

我没有测试过这个,但看起来它应该可以工作.

I've not tested this but it looks like it should work.

这里的参考是 useRef 文档.

这篇关于如何使用 useEffect setParams 并避免获得无限渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆