这是我的应用程序的外观。
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 (...)