根据文件:
componentDidUpdate()更新发生后立即调用.初始渲染不会调用此方法.
我们可以使用新的useEffect()钩子来模拟componentDidUpdate(),但似乎useEffect()是在每次渲染之后运行,甚至是第一次.如何让它不能在初始渲染上运行?
正如您在下面的示例中所看到的,componentDidUpdateFunction在初始渲染期间打印,但componentDidUpdateClass在初始渲染期间未打印.
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log("componentDidUpdateClass");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => { …Run Code Online (Sandbox Code Playgroud)我有一个名为“Causes”的父组件和一个名为“Graph”的子组件,
有一个名为“datas”的钩子,它是在“Causes”(父级)中创建和更新的,我将其作为 props 传递给“Graph”(子级)。
第一次,一切正常,但是当我更新“Causes”(父级)中的“datas”时,“Graph”(子级)仍然具有旧的“datas”对象数组。
如何强制重新渲染子组件?
const [datas, setDatas] = useState([
{ shop: "00h-8h", value: 250, color: "#A2AAC2" },
{ shop: "8h-12h", value: 420, color: "#A2AAC2" },
{ shop: "12h-16h", value: 500, color: "#A2AAC2" },
{ shop: "16h-20h", value: 80, color: "#A2AAC2" },
{ shop: "20h-00h", value: 80, color: "#A2AAC2" }
]);
useEffect(() => {
setDatas(newArray); <- this updates data, but the component below always got the old datas
}, []);
return (
<Graph
h={400}
w={900}
data={datas}
defaultKeys={["shop", "value"]}
/> …Run Code Online (Sandbox Code Playgroud)