为什么 React List 组件会渲染两次?
Why the React List component gets rendered twice?
我有一个 React 代码如下:
import React, { useState, useCallback } from "react";
const initialUsers = [
{
id: "1",
name: "foo",
},
{
id: "2",
name: "bar",
},
];
const List = React.memo(({ users, onRemove }) => {
console.log("rendering list");
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} <span onClick={() => onRemove(user.id)}>X</span>
</li>
))}
</ul>
);
});
const App = () => {
const [users, setUsers] = useState(initialUsers);
const [text, setText] = useState("");
const handleRemove = useCallback(
(userId) => {
console.log("handleRemove", userId);
const filteredUsers = users.filter((user) => user.id !== userId);
setUsers(filteredUsers);
},
[users]
);
const handleText = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={handleText} />
<List users={users} onRemove={handleRemove} />
</div>
);
};
export default App;
当我第一次加载页面时,我看到 rendering list
在浏览器控制台中被转储了两次,请参阅 https://codesandbox.io/s/elegant-bash-ic9uqv?file=/src/App.js
这是为什么?
那是因为您在 index.js
中使用了 StrictMode
使用StrictMode
时,生命周期方法被调用两次。
它发生在你的生命周期方法中 detecting unexpected side effects。
我有一个 React 代码如下:
import React, { useState, useCallback } from "react";
const initialUsers = [
{
id: "1",
name: "foo",
},
{
id: "2",
name: "bar",
},
];
const List = React.memo(({ users, onRemove }) => {
console.log("rendering list");
return (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} <span onClick={() => onRemove(user.id)}>X</span>
</li>
))}
</ul>
);
});
const App = () => {
const [users, setUsers] = useState(initialUsers);
const [text, setText] = useState("");
const handleRemove = useCallback(
(userId) => {
console.log("handleRemove", userId);
const filteredUsers = users.filter((user) => user.id !== userId);
setUsers(filteredUsers);
},
[users]
);
const handleText = (event) => {
setText(event.target.value);
};
return (
<div>
<input type="text" value={text} onChange={handleText} />
<List users={users} onRemove={handleRemove} />
</div>
);
};
export default App;
当我第一次加载页面时,我看到 rendering list
在浏览器控制台中被转储了两次,请参阅 https://codesandbox.io/s/elegant-bash-ic9uqv?file=/src/App.js
这是为什么?
那是因为您在 index.js
StrictMode
使用StrictMode
时,生命周期方法被调用两次。
它发生在你的生命周期方法中 detecting unexpected side effects。