在 useEffect 2nd param 中使用对象而不必将其字符串化为 JSON [英] use object in useEffect 2nd param without having to stringify it to JSON
问题描述
在 JS 中,两个对象不相等.
In JS two objects are not equals.
const a = {}, b = {};
console.log(a === b);
所以我不能在 useEffect
(React hooks)中使用一个对象作为第二个参数,因为它总是被认为是 false(所以它会重新渲染):
So I can't use an object in useEffect
(React hooks) as a second parameter since it will always be considered as false (so it will re-render):
function MyComponent() {
// ...
useEffect(() => {
// do something
}, [myObject]) // <- this is the object that can change.
}
这样做(上面的代码),会导致每次组件重新渲染的运行效果,因为每次都认为对象不相等.
Doing this (code above), results in running effect everytime the component re-render, because object is considered not equal each time.
我可以通过将对象作为 JSON 字符串化值传递来破解"这一点,但 IMO 有点脏:
I can "hack" this by passing the object as a JSON stringified value, but it's a bit dirty IMO:
function MyComponent() {
// ...
useEffect(() => {
// do something
}, [JSON.stringify(myObject)]) // <- yuck
有没有更好的方法来做到这一点并避免不必要的效果调用?
Is there a better way to do this and avoid unwanted calls of the effect?
旁注:对象具有嵌套属性.效果必须在此对象内的每个更改上运行.
推荐答案
您可以创建一个自定义挂钩来跟踪 ref
中的先前依赖项数组,并将对象与例如Lodash isEqual
并且只运行提供的函数,如果它们不是相等.
You could create a custom hook that keeps track of the previous dependency array in a ref
and compares the objects with e.g. Lodash isEqual
and only runs the provided function if they are not equal.
示例
const { useState, useEffect, useRef } = React;
const { isEqual } = _;
function useDeepEffect(fn, deps) {
const isFirst = useRef(true);
const prevDeps = useRef(deps);
useEffect(() => {
const isFirstEffect = isFirst.current;
const isSame = prevDeps.current.every((obj, index) =>
isEqual(obj, deps[index])
);
isFirst.current = false;
prevDeps.current = deps;
if (isFirstEffect || !isSame) {
return fn();
}
}, deps);
}
function App() {
const [state, setState] = useState({ foo: "foo" });
useEffect(() => {
setTimeout(() => setState({ foo: "foo" }), 1000);
setTimeout(() => setState({ foo: "bar" }), 2000);
}, []);
useDeepEffect(() => {
console.log("State changed!");
}, [state]);
return <div>{JSON.stringify(state)}</div>;
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
这篇关于在 useEffect 2nd param 中使用对象而不必将其字符串化为 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!