在类组件中,setState()
方法可以采用回调函数,但在函数组件中,当我向服装设置状态提供回调时,会出现以下警告: 警告:来自useState()
和useReducer()
Hook 的状态更新不支持第二个回调参数。要在渲染后执行副作用,请使用useEffect()
在组件主体中声明它。 我需要设置我的状态,然后页面将重定向。但我没有任何想法。
与其传递callback
函数,不如使用useEffect
hook,并执行类似操作以实现所需的结果。
useEffect(() => {
console.log('state changed', your-state-variable)
// write your callback function here
}, [your-state-variable]);
小心!在类组件中,可以在所需的每个setState
之后立即调用回调函数,但在功能组件中,useEffect
钩在整个组件中发生的任何更改状态后运行。 要应对此挑战,您应该谨慎选择状态以及如何设置状态。
这是一个非常简单的例子:
import { Grid, Button, Typography } from "@material-ui/core";
import { Component, useState, useEffect } from "react";
export const FunctionComponent = () => {
const [count, setCount] = useState(0);
const [background, setBackground] = useState("white");
useEffect(() => {
setTimeout(() => setBackground("white"), 100);
}, [background]);
const countIncreamentHandler = () => {
setCount((count) => count + 1);
setBackground("rgba(112, 181, 0, .2)");
};
const countDecreamentHandler = () => {
setCount((count) => count - 1);
setBackground("rgba(181, 9, 0, .2)");
};
return (
<Grid container justify="space-around">
<Button
variant="contained"
color="primary"
onClick={countIncreamentHandler}
>
+
</Button>
<Typography style={{ padding: 5, background }} variant="h5">
{count}
</Typography>
<Button
variant="contained"
color="secondary"
onClick={countDecreamentHandler}
>
-
</Button>
</Grid>
);
};
在类组件中:
export class ClassCompontet extends Component {
constructor() {
super();
this.state = {
count: 0,
background: "white"
};
}
countIncreamentHandler = () => {
this.setState(
(prevState) => ({
count: prevState.count + 1,
background: "rgba(112, 181, 0, .2)"
}),
() => {
setTimeout(() => {
this.setState({ background: "white" });
}, 100);
}
);
};
countDecreamentHandler = () => {
this.setState(
(prevState) => ({
count: prevState.count - 1,
background: "rgba(181, 9, 0, .2)"
}),
() => {
setTimeout(() => {
this.setState({ background: "white" });
}, 100);
}
);
};
render() {
return (
<Grid container justify="space-around">
<Button
variant="contained"
color="primary"
onClick={this.countIncreamentHandler}
>
+
</Button>
<Typography
style={{ padding: 5, background: this?.state?.background }}
variant="h5"
>
{this?.state?.count}
</Typography>
<Button
variant="contained"
color="secondary"
onClick={this.countDecreamentHandler}
>
-
</Button>
</Grid>
);
}
}