react——当组件重新呈现时,如何使变量的值保持不变



这是我的应用程序的外观。

App.js

const Home = () => {
const [inputValues, setInputValues] = useState(...);
const word = generateRandomWord(); // how to make the word not changing 
return (...)

generateRandowWord.js

export const generateRandomWord = () => {
// return a random word in string
}

每次inputValues变化,Home分量都会被重新渲染,word的值也不同。如何使word的值保持不变?

您可以使用useMemo钩子:

const word = useMemo(() => generateRandomWord(), []);

当依赖项数组中的值发生变化时,将重新生成单词。如果你传递一个空数组,该值在渲染器之间将始终保持不变。

https://reactjs.org/docs/hooks-reference.html usememo

您还可以考虑将结果存储在一个状态中,以便您可以在以后需要时更改它

const Home = () => {
const [inputValues, setInputValues] = useState(...);
const [word, updateWord] = useState(generateRandomWord()); 
return (...)

最新更新