使用状态和回调函数

useState and callback function

在 class 组件中,setState() 方法可以采用回调函数,但是在功能组件中,当我对服装 setState 进行回调时,会出现此警告: 警告:来自 useState()useReducer() 挂钩的状态更新不支持第二个回调参数。要在渲染后执行副作用,请在组件主体中使用 useEffect() 声明它。 我需要设置状态,然后页面将重定向。但是我不知道。

不要传递 callback 函数,而是使用 useEffect 钩子,做一些这样的事情来达到预期的结果。

 useEffect(() => {
    console.log('state changed', your-state-variable)
    // write your callback function here
  }, [your-state-variable]);

小心!在 class 组件中,您可以在每个 setState 之后立即调用回调函数,但在功能组件中, useEffect 挂钩 运行 在任何更改状态之后这发生在你的整个组件中。 要应对这一挑战,您应该谨慎选择您的状态以及如何设置它。

This是一个很简单的例子:

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>
    );
  }
}