我在用着react-navigation
我有一个动态标题,所以我使用setParams
并将其放在标题中。
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/exhaustive-deps)
)并说我需要添加navigation
到依赖数组。
如果我添加navigation
到依赖数组,就会变成无限循环。
setParam
更新=>navigation
打电话=>setParam
更新=>navigation
并继续...
我怎样才能打电话setParam
仅一次并避免正确地响应钩子规则?
Could useRef
按照底部的建议解决这个问题answer https://stackoverflow.com/questions/56243575/is-there-a-proper-way-to-use-usenavigation-hook-with-useeffect-dependencies#answer-56245870?
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')
})
我还没有测试过这个,但看起来应该可以工作。
作为参考,这里有使用参考文档 https://reactjs.org/docs/hooks-reference.html#useref.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)