如何在功能组件中只提取一次值?



我试图从json文件中提取一个值只有一次。这意味着我不希望它在组件被重新渲染后做同样的工作。我试着用useEffect()虽然由于某种原因,值没有被提取,我得到一个空对象。

import quotes from '../quotes.json'
function Header () {
var currentQuote = {}

useEffect(() => {
currentQuote = quotes.listOfQuotes[Math.floor(Math.random() * quotes.listOfQuotes.length)]
}, [])
}

useMemo将工作。与useEffect类似,它只会在依赖项数组改变时运行,所以如果您传递一个空的依赖项数组,它只会在mount时运行。

var currentQuote = useMemo(() => (
quotes.listOfQuotes[Math.floor(Math.random() * quotes.listOfQuotes.length)]
), []);

如果你想让它在视图中呈现,你需要在状态中设置你的值。你已经给了一个空数组作为useEffect的深度,所以它不会在每次渲染时被触发。这是一个Stackblitz的副本,下面是代码:

function Header() {
const [currentQuote, setCurrentQuote] = React.useState('');
const [val, setVal] = React.useState(0);
const quotes = {
listOfQuotes:['lol', 'test', 'another value', 'super quote']
};
React.useEffect(() => {
console.log('Math.floor(Math.random() * quotes.listOfQuotes.length) = ', Math.floor(Math.random() * quotes.listOfQuotes.length))
setCurrentQuote(
quotes.listOfQuotes[
Math.floor(Math.random() * quotes.listOfQuotes.length)
]);
}, []);
return (
<>
<button onClick={() => setVal(3)}>Edit val</button><br />
{currentQuote}<br />
{val}
</>
)
}

最新更新