reactjs - 如何区分useEffect是否被路由改变触发
问题描述
据我所知,useEffect 可以由以下条件触发
- 依赖改变
- 路线变更
- 初始渲染
我有以下组件,data
是一个复杂的对象。当它被路由更改触发时,data
prop 具有缓存值。其他所有内容,例如 state、ref 都会被重置。
const App = memo(({ data }}) => {
useEffect(() => {
// if triggered by route change, do thing
}, [data]);
return (<div />)
});
区分路由更改是否调用 useEffect 的最佳方法是什么?
解决方案
尝试将location
其作为依赖项:
useEffect(() => {
// ...
}, [location]);
编辑 如果要排除此依赖项,可以执行以下操作:
const [flag, setFlag] = useState(true);
useEffect(() => {
setFlag(false);
}, [location]);
useEffect(async () => {
await setTimeout(() => undefined, 500); //sleep to wait for other useEffect() to set a flag or not
if (flag) { /* do sth that is not invoked by a location change */ }
else {
setFlag(true);
}
}, [data]);
编辑2
我在官方文档https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state
这样你就可以构造一个componentDidUpdate(prevProps)
钩子,所以你的代码看起来像:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
useEffect(() => {
const prevLocation = usePrevious(location);
if (location === prevLocation)
//the body of your function
}, [data]);
推荐阅读
- docker - 由于 docker 数据目录在节点上移动,服务/部署间歇性卡在 ContainerCreating 上的问题
- bash - 以 sudo 执行时,进程替换显示语法错误
- json - 即使我拥有存储桶并拥有所有权限,我也会收到错误“访问被拒绝”
- python - 如何以编程方式响应从标准输入请求输入的 Python 库?
- javascript - 事件侦听器包装函数 - 事件侦听器为元素绑定了多次
- azure - 如何加快 Cosmos DB 聚合查询?
- sql - 需要有关 SQL 查询的帮助以查找具有最大数量的元组
- python-3.x - 如何在Python中计算列的段中的特定数字
- apache-spark - org.apache.spark.SparkException:无法执行用户定义的函数(如何找到有问题的 udf)
- machine-learning - 机器学习中的多项式和多项式回归有什么区别?