我有一个组件,我设置了一个计数,并在单击按钮时更新状态。 但是,当我检查渲染时间时,每次单击按钮都会渲染两次。
https://codesandbox.io/s/brave-forest-yre6y?file=/src/App.js
export default function App() {
const cute = Array(10).fill({});
const [count, setCount] = useState(2);
console.log(count);
return (
<div className="App">
<button
onClick={() => {
if (count < 10) setCount(count + 1);
}}
>
add
</button>
{cute.map((data, index) => {
if (index < count) {
return (
<div>
<p>{index}. Luna is cute</p>
</div>
);
}
})}
</div>
);
}
我想知道:
答案 0 :(得分:4)
您的应用正在使用"d/M/yyyy"
。查看您的StrictMode
文件-您的应用包裹在index.js
元素之间。
使用<React.StrictMode>
将使您的应用渲染两次,但只能在开发模式下进行。使用StrictMode
创建应用将默认启用严格模式。
这是严格模式下的official docs。
解决方案只是删除create-react-app
,但这也将失去其某些优势,因此,如果它不打扰您,我将保持现状,因为它不会像在生产中。
有关更多详细信息,请参见此相关问题:My React Component is rendering twice because of Strict Mode
答案 1 :(得分:2)
很明显,重新渲染绝对不是错误,也不是与库的渲染机制有关的东西。相反,它是React?
提供的调试机制。推荐此博客https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/ 您将获得更好的理解。
您可以禁用strictmode,请参考此沙盒链接。它只会呈现一次。
https://codesandbox.io/s/snowy-violet-eo70o?file=/src/index.js