[英]Why is react component function executed even when the state variable value is not changed?
I used npx create-react-app
to create a react app.我使用
npx create-react-app
创建了一个反应应用程序。 Following are the index.js and App.js code:以下是 index.js 和 App.js 代码:
Index.js (did not use StrictMode) Index.js (未使用 StrictMode)
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<App />
);
App.js应用程序.js
import {useState} from 'react';
function App() {
console.log('App component function executed');
const [name, setName] = useState('name');
const changeNameHandler = () => {
setName('newname');
}
return (
<div className="App">
{name}
<button onClick={changeNameHandler}>Change Name</button>
</div>
);
}
export default App;
When I start the app I see 'App component function executed' in the console for the first time which is expected.当我启动应用程序时,我第一次在控制台中看到“应用程序组件功能已执行”,这是预期的。 Then I click the 'Change Name' button and see another 'App component function executed' in the console, still expected.
然后我单击“更改名称”按钮并在控制台中看到另一个“应用程序组件功能已执行”,这仍然是预期的。
At this point the state has been set to 'newname' so when I click the button again, new message should not be logged in the console, but it again consoles 'App component function executed'.此时状态已设置为“新名称”,因此当我再次单击该按钮时,不应在控制台中记录新消息,但它再次控制台“应用程序组件功能已执行”。 Clicking the button further doesn't do anything.
进一步单击该按钮不会执行任何操作。
I expected that 'App component function executed' would be logged only 2 time (first at initial mounting and when the button is clicked the first time).我预计“执行的应用程序组件功能”只会记录 2 次(第一次是在初始安装时,然后是第一次单击按钮时)。 Or it would be logged every time I click the button.
或者每次单击按钮时都会记录下来。 But I see it logging exactly 3 times.
但我看到它记录了 3 次。
Can someone explain this behavior?有人可以解释这种行为吗?
Every time the button is clicked, the state is set.每次单击按钮时,都会设置状态。 Even tho it is being set to the same string, the state is still changing and thus causing that component to re-render.
即使它被设置为相同的字符串,状态仍在变化,从而导致该组件重新渲染。 This is why you are seeing the console log every time the button is clicked.
这就是每次单击按钮时都会看到控制台日志的原因。
useState doesn't have its own memoization built-in. useState 没有内置的自己的 memoization。 As you are setting the state to the same string on the button click, look into memoization in react.
当您在按钮单击时将状态设置为相同的字符串时,请查看反应中的记忆。 This should solve this problem
这应该可以解决这个问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.