gpt4 book ai didi

reactjs - useMemo 具有数组依赖性?

转载 作者:行者123 更新时间:2023-12-04 11:55:10 29 4
gpt4 key购买 nike

你能有一个数组作为 useMemo 的依赖吗?钩?
我知道这会很好:

const dep1 : string = '1'

const thing = useMemo(()=>{
// stuff
},[dep1])
但是这个呢?:
const dep2 : string[] = ['1', '2']

const thing2 = useMemo(()=>{
// stuff
},[dep2])
我以为我读过一次,对象和数组总是会为相等检查返回 false,实际上意味着 thing2永远不会被记住。但是我在文档中看不到这一点:
https://reactjs.org/docs/hooks-reference.html#usememo
这是一个人为的例子,如 dep1dep2是常量变量,但想象它们是一个值会改变的 Prop 。

最佳答案

我想我被 React.memo 弄糊涂了,来自文档:

By default it will only shallowly compare complex objects in the props object. If you want control over the comparison, you can also provide a custom comparison function as the second argument.

function MyComponent(props) {
/* render using props */
}
function areEqual(prevProps, nextProps) {
/*
return true if passing nextProps to render would return
the same result as passing prevProps to render,
otherwise return false
*/
}
export default React.memo(MyComponent, areEqual);
useMemo似乎可以很好地使用数组作为依赖项:
https://codesandbox.io/s/mystifying-cori-jr0vi?file=/src/App.js:0-647
import React, { useState, useMemo } from "react";
import "./styles.css";

export default function App() {
console.log("App rendered");
const [st, setStr] = useState("0");
const [arr, setArr] = useState([1]);

const thingToRender = useMemo(() => {
console.log("thingToRender ran");
return `Array length is ${arr.length}`;
}, [arr]);

return (
<div className="App">
<button onClick={() => setStr(`${Math.random()}`)}>Change str</button>
<h1>{st}</h1>
<p>{thingToRender}</p>
<button onClick={() => setArr([...arr, Math.round(Math.random() * 10)])}>
Change arr
</button>
</div>
);
}
但是值得一提的是,如果您 map 它将无法工作。 (或其他创建新数组的方法):
https://codesandbox.io/s/silent-silence-91j8s?file=/src/App.js
import React, { useState, useMemo } from "react";
import "./styles.css";

export default function App() {
console.log("App rendered");
const [st, setStr] = useState("0");
const [arr, setArr] = useState([1]);

const arr2 = arr.map((item) => item);

const thingToRender = useMemo(() => {
console.log("thingToRender ran");
return `Array length is ${arr2.length}`;
}, [arr2]);

return (
<div className="App">
<button onClick={() => setStr(`${Math.random()}`)}>Change str</button>
<h1>{st}</h1>
<p>{thingToRender}</p>
<button onClick={() => setArr([...arr, Math.round(Math.random() * 10)])}>
Change arr
</button>
</div>
);
}

关于reactjs - useMemo 具有数组依赖性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65125885/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com