【问题标题】:Call Function On Mount in ReactJS在 ReactJS 中调用挂载函数
【发布时间】:2020-05-27 04:28:12
【问题描述】:

在 ReactJS 上加载组件时调用函数时出现问题。我尝试使用 componentDidMount() 并且编译时出错。请在下面检查我的代码。谢谢

export default function Customers() {
    const classes = useStyles();
    const searchBarStyles = useStyles2();
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const dispatch = useDispatch();

    const handleChangePage = (event, newPage) => {
      setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
      setRowsPerPage(+event.target.value);
      setPage(0);
    };

    const fetch = () => {
      dispatch(fetchPendingAdmissions());
    };

    componentDidMount() {
        fetch()
    }

    return (
      <div>
        <h1 className={classes.h1}>Customers</h1>
        <Paper component="form" className={searchBarStyles.root}>
          <InputBase
            className={searchBarStyles.input}
            placeholder="Search..."
            inputProps={{ 'aria-label': 'search...' }}
          />
          <IconButton type="submit" className={searchBarStyles.iconButton} aria-label="search">
            <SearchIcon />
          </IconButton>
        </Paper>
        <Paper className={classes.root}>
          <TableContainer className={classes.container}>
            <Table stickyHeader aria-label="sticky table">
              <TableHead>
                <TableRow>
                  <TableCell>Name</TableCell>
                  <TableCell>ID</TableCell>
                  <TableCell>Order Date</TableCell>
                  <TableCell>Actions</TableCell>
                  <TableCell></TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                <TableRow>
                  <TableCell>Robert</TableCell>
                  <TableCell>1324171354</TableCell>
                  <TableCell>07-21-20</TableCell>
                  <TableCell>
                    <Button onClick={fetch} variant="contained" color="primary" startIcon={<VisibilityIcon />}>
                      View
                    </Button>
                  </TableCell>
                  <TableCell>
                    <Button variant="contained" className={classes.buttonSuccess} startIcon={<ThumbUpIcon />}>
                      Approve
                    </Button>
                    <Button variant="contained" className={classes.buttonError} startIcon={<CancelIcon />}>
                      Decline
                    </Button>
                  </TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions={[10, 25, 100]}
            component="div"
            count={10}
            rowsPerPage={rowsPerPage}
            page={page}
            onChangePage={handleChangePage}
            onChangeRowsPerPage={handleChangeRowsPerPage}
          />
        </Paper>
      </div>
    );
  }

【问题讨论】:

    标签: reactjs react-redux react-lifecycle react-lifecycle-hooks


    【解决方案1】:

    componentDidMount() 生命周期方法仅用于基于类的组件中。您可以使用带有空依赖数组的 useEffect 钩子在组件挂载时加载您的函数。

    import React, {useState, useEffect} from 'react'
    
    useEffect(() => {
      fetch();
    }, []);
    

    注意:useEffectuse side effect 的缩写。 useEffect 允许我们组合 componentDidMountcomponentDidUpdate 生命周期方法。

    陷阱:

    • 如果不将任何变量传递给依赖数组,它只会在第一次渲染时被调用,就像componentDidMount 一样,否则每次依赖数组中的值发生变化时都会触发挂钩。
    • 如果您不将数组传递给useEffect 挂钩,则会重复重新加载组件。

    【讨论】:

      【解决方案2】:

      您不能在功能组件中使用诸如 componentDidMount 之类的生命周期方法。你必须使用useEffect

      您的更新代码

      import React, {useEffect} from 'react'
      export default function Customers() {
          const classes = useStyles();
          const searchBarStyles = useStyles2();
          const [page, setPage] = React.useState(0);
          const [rowsPerPage, setRowsPerPage] = React.useState(10);
          const dispatch = useDispatch();
      
          const handleChangePage = (event, newPage) => {
            setPage(newPage);
          };
      
          const handleChangeRowsPerPage = (event) => {
            setRowsPerPage(+event.target.value);
            setPage(0);
          };
      
          const fetch = () => {
            dispatch(fetchPendingAdmissions());
          };
      
          useEffect(() => {
              fetch().then(result => {
                  setRowsPerPage(result.blah)
              })
          }, [])
      
          // componentDidMount() { //<--------- remove this.
          //     fetch()
          // }
      
          return (
            <div>
       ....
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-31
        • 2020-09-09
        • 2014-10-22
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        相关资源
        最近更新 更多