我正在按照本教程演示 react 的“useCallback”钩子以及 React.memo,以防止不必要地渲染函数。为了证明这个概念,我们使用 useRef 来控制渲染的数量。这仅适用于该功能,但我添加了一个随机化按钮背景颜色的功能,我似乎无法阻止这两个功能的呈现。
import React,{useState, useCallback, useRef} from 'react';
import './App.css';
const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`
const Button = React.memo(({increment, bgColor}) => {
const count = useRef(0)
console.log(count.current++)
return(
<button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
)
})
const App = React.memo(() => {
const [count, setCount] = useState(0)
const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)
const increment = useCallback(() => {
setCount(previousCount => previousCount + 1)
setColor(randomColor)
},[setCount,setColor])
return (
<div className="App">
<header className="App-header">
<h2>{count}</h2>
<Button increment={increment} bgColor={color}>increment</Button>
</header>
</div>
);
})
export default App;
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
import React,{useState, useCallback, useRef} from 'react';
import './App.css';
const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`
const Button = React.memo(({increment, bgColor}) => {
const count = useRef(0)
console.log(count.current++)
return(
<button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
)
})
const App = React.memo(() => {
const [count, setCount] = useState(0)
const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)
const increment = useCallback(() => {
setCount(previousCount => previousCount + 1)
setColor(randomColor)
},[setCount,setColor])
return (
<div className="App">
<header className="App-header">
<h2>{count}</h2>
<Button increment={increment} bgColor={color}>increment</Button>
</header>
</div>
);
})
export default App;