我正在使用简单的React组件来了解何时进行渲染。
Sample 1-最初渲染一次。无论单击按钮多少次,都不会渲染。这是预期的。
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [state, setState] = useState([
{ id: 1, name: "test1" },
{ id: 2, name: "test2" }
]);
const onClick = () => setState(data => data);
console.log("App rendered");
return (
<div className="App">
<h1>Test if setting same data causes re-rendering</h1>
<button onClick={onClick}>Call setState with same data</button>
{state.map(({ id, name }) => (
<p key={id}>{name}</p>
))}
</div>
);
}
Sample 2-自useEffect
用值更新setMessages
以来,最初渲染两次。这是预期的。但是,如果该按钮被单击1次以上,它将呈现一次。由于设置了相同的值,因此甚至不应重新渲染。 如果没有新值/引用被更新,为什么会呈现?
import React, { useState, useEffect, useMemo, useCallback } from "react";
import axios from "axios";
import "./styles.css";
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
export default function App() {
const [messages, setMessages] = useState([]);
useEffect(() => {
axios
.get(`https://api.myjson.com/bins/10xva4`)
.then(({ data: { messages } }) => setMessages(messages));
}, []);
const Display = useMemo(
() =>
messages.map(({ content, senderUuid, sentAt }, index) => {
let d = new Date(sentAt);
return (
<div className="container" key={index}>
<p>Content: {content}</p>
<p>SenderUuid: {senderUuid}</p>
<p>DayOfTheWeek: {d.getDate()}</p>
<p>Month: {d.getMonth()}</p>
<p>Day: {days[d.getDay()]}</p>
<p>Year: {d.getFullYear()}</p>
</div>
);
}),
[messages]
);
const onClick = useCallback(() => setMessages(messages => messages), []);
console.log("App rendered");
// console.log({ messages });
return useMemo(
() => (
<div className="App">
<button onClick={onClick}>Call setMessages with same data</button>
{Display}
</div>
),
[Display, onClick]
);
}
更新:通过react确认了它的错误。 -https://github.com/facebook/react/issues/18098