【问题标题】:TypeError: props.pagination is undefinedTypeError: props.pagination 未定义
【发布时间】:2020-10-05 14:31:29
【问题描述】:

我正在尝试获取来自 redux 存储的页面数据并将其传递给名为 pagination 的本地状态。这个分页状态被进一步传递给子组件。但是问题是每当我尝试将 redux 状态传递给本地状态时,我都会收到未定义的错误。这里定义了数据,我可以控制台记录数据,但它会延迟我可能会收到错误的原因。我不知道如何解决这个问题。我正在使用反应功能组件。

newOrder.js

  const [pagination, setPagination] = React.useState({});

  const DataReceived = (state) =>
    state.OrderAndShipping.NewOrderList.newOrder._embedded;
  const selectedData = useSelector(DataReceived, shallowEqual);
  const NewOrder = selectedData ? selectedData.customerOrderResourceList : null;

  const pageState = (state) =>
    state.OrderAndShipping.NewOrderList.newOrder.page;
  const selectPage = useSelector(pageState);

  console.log("page", selectPage);

  React.useEffect(() => {
    const access_token = localStorage.getItem("access_token");
    props.getNewOrderList(access_token, "", "");         <-- redux dispatch function
  }, []);

  React.useEffect(() => {
    setPagination(selectPage);    <-- Here i am trying to pass redux state to localstate.
  }, []);



const mapStateProps = (state) => {
  console.log(state);
  return {
    newOrder: state.OrderAndShipping.NewOrderList.newOrder
      ? state.OrderAndShipping.NewOrderList.newOrder._embedded
      : null,
  };
};
const mapDispatchToProps = {
  getNewOrderList,          <-- Dispatching function  
};

通过

{TableData && TableData.rows && TableData.rows.length > 0 && (
        <Table
          _handleCheckbox={_handleCheckbox}
          _handlePagination={_handlePagination}
          _handleUserCheckBox={_handleUserCheckBox}
          data={TableData}
          pagination={pagination}
        />
      )}

Table.js

    const emptyRows =
    rowsPerPage -
    Math.min(
      rowsPerPage,
      props.data.rows.length - props.pagination.number * rowsPerPage
    );


  const { number } = props.pagination;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <EnhancedTableToolbar numSelected={selected.length} data={props.data} />
        <div className={classes.tableWrapper}>
          <Table
            className={classes.table}
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
          >
            {/*//! Table Head Component */}
            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={props.data.rows.length}
              data={props.data}
            />
            {/*//! Table Body Component */}
            <TableBody>
              {stableSort(props.data.rows, getSorting(order, orderBy))
                .slice(number * rowsPerPage, number * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <TableRow
                      hover
                      onClick={(event) =>
                        handleClick(event, row.name, row.userId)
                      }
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={props.data.rows.name}
                      selected={isItemSelected}
                    >

                    </TableRow>
                  );
                })}
              {emptyRows > 0 && (
                <TableRow style={{ height: 49 * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        {/**
         * ===============================================
         *  PAGINATION
         * =============================================
         */}
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={props.data.rows.length}
          rowsPerPage={rowsPerPage}
          page={props.pagination.number}
          backIconButtonProps={{
            "aria-label": "Previous Page",
          }}
          nextIconButtonProps={{
            "aria-label": "Next Page",
          }}
          onChangePage={props._handlePagination}
          onChangeRowsPerPage={handleChangeRowsPerPage}
        />
      </Paper>

console.log 分页

console.log("page", selectPage);

Table.js

function EnhancedTable(props) {

  const [rowsPerPage, setRowsPerPage] = React.useState(10);


  //! Select All Checkbox
  function handleSelectAllClick(event) {
    if (event.target.checked) {
      const newSelecteds = props.data.rows.map((n) => n.name);
      setSelected(newSelecteds);
      return;
    }
    setSelected([]);
  }

  //! Handle CheckBox here
  function handleClick(event, name, userId) {
    const selectedIndex = selected.indexOf(name);
    let newSelected = [];
    const selectedIdIndex = SelectedId.indexOf(userId);

    let newSelectedIndex = [];

    console.log(userId);
    let userid = [];
    userid = userId;
    console.log(selectedIndex);

    props._handleCheckbox(selectedIdIndex, userid, SelectedId);





  function handleChangeDense(event) {
    setDense(event.target.checked);
  }

  const isSelected = (name) => selected.indexOf(name) !== -1;

  const emptyRows =
    rowsPerPage -
    Math.min(
      rowsPerPage,
      props.data.rows.length - props.pagination.number * rowsPerPage
    );



  const { number } = props.pagination;
  return (
    <div className={classes.root}>
      <Paper className={classes.paper}>
        <EnhancedTableToolbar numSelected={selected.length} data={props.data} />
        <div className={classes.tableWrapper}>
          <Table
            className={classes.table}
            aria-labelledby="tableTitle"
            size={dense ? "small" : "medium"}
          >

            <EnhancedTableHead
              numSelected={selected.length}
              order={order}
              orderBy={orderBy}
              onSelectAllClick={handleSelectAllClick}
              onRequestSort={handleRequestSort}
              rowCount={props.data.rows.length}
              data={props.data}
            />
            {/*//! Table Body Component */}
            <TableBody>
              {stableSort(props.data.rows, getSorting(order, orderBy))
                .slice(number * rowsPerPage, number * rowsPerPage + rowsPerPage)
                .map((row, index) => {
                  const isItemSelected = isSelected(row.name);
                  const labelId = `enhanced-table-checkbox-${index}`;

                  return (
                    <TableRow
                      hover
                      onClick={(event) =>
                        handleClick(event, row.name, row.userId)
                      }
                      role="checkbox"
                      aria-checked={isItemSelected}
                      tabIndex={-1}
                      key={props.data.rows.name}
                      selected={isItemSelected}
                    >
                      <TableCell padding="checkbox">
                        <Checkbox
                          checked={isItemSelected}
                          inputProps={{ "aria-labelledby": labelId }}
                        />
                      </TableCell>
                      {rowData(row)}
                    </TableRow>
                  );
                })}
              {emptyRows > 0 && (
                <TableRow style={{ height: 49 * emptyRows }}>
                  <TableCell colSpan={6} />
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        {/**
         * ===============================================
         *  PAGINATION
         * =============================================
         */}
        <TablePagination
          rowsPerPageOptions={[5, 10, 25]}
          component="div"
          count={props.data.rows.length}
          rowsPerPage={rowsPerPage}
          page={props.pagination.number}
          backIconButtonProps={{
            "aria-label": "Previous Page",
          }}
          nextIconButtonProps={{
            "aria-label": "Next Page",
          }}
          onChangePage={() => props.handlePagination()}
          onChangeRowsPerPage={handleChangeRowsPerPage}
        />
      </Paper>
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    checkbox: state.AllUsers.Admin.checkBox,
  };
};
export default connect(mapStateToProps, {})(EnhancedTable);

【问题讨论】:

  • 请分享您传递分页的代码
  • 你在哪里使用了 props.pagination 行
  • @RIYAJKHAN 更新了我的代码看看。
  • @JovylleBermudez 看看
  • 检查答案@adityakumar

标签: javascript reactjs redux react-redux react-functional-component


【解决方案1】:

问题:

根据您的控制台日志,您最初得到的 selectPage 未定义,并且您还设置了仅在挂载时的值

React.useEffect(() => {
    setPagination(selectPage);    <-- Here i am trying to pass redux state to localstate.
}, []); // <--- this will executed only on mount

解决方案:

我认为你应该留意selectPage 中的变化,只有在可用时才更新

React.useEffect(() => {
    if(selectPage) { // <--- check if available
       setPagination(selectPage);
    }
}, [selectPage]); // <--- will run useEffect on everychange of `selectPage`

【讨论】:

  • 仍然遇到同样的错误TypeError: props.pagination is undefined
  • @adityakumar,可以创建一个工作演示,pagination 并发布完整的table.js 代码,想看看你是如何获得道具的
  • 我正在使用 enhancedPagination 来自 Material ui material-ui.com/components/tables/#table
  • 请在代码和框上创建一个工作演示,不知何故您设置了未定义的分页,或者您错误地传递了值或错误地访问了传递的值。
猜你喜欢
  • 2017-06-22
  • 2018-10-12
  • 2014-08-14
  • 2014-06-21
  • 2014-08-06
  • 2022-10-13
  • 2018-06-02
  • 2017-02-18
  • 2012-12-30
相关资源
最近更新 更多