首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError: props.pagination未定义

TypeError: props.pagination未定义
EN

Stack Overflow用户
提问于 2020-06-16 04:06:35
回答 1查看 732关注 0票数 0

我正在尝试获取来自redux存储的页面数据,并将其传递给名为pagination的本地状态。此分页状态将进一步传递给子组件。但问题是,每当我试图将redux状态传递给本地状态时,就会得到未定义的错误。在这里,数据是定义的,我可以console.log数据,但它会延迟,为什么我可能会得到错误。我不知道怎么解决这个问题。我使用的是反应功能组件。

newOrder.js

代码语言:javascript
复制
  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  
};

传递

代码语言:javascript
复制
{TableData && TableData.rows && TableData.rows.length > 0 && (
        <Table
          _handleCheckbox={_handleCheckbox}
          _handlePagination={_handlePagination}
          _handleUserCheckBox={_handleUserCheckBox}
          data={TableData}
          pagination={pagination}
        />
      )}

Table.js

代码语言:javascript
复制
    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分页

代码语言:javascript
复制
console.log("page", selectPage);

Table.js

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

发布于 2020-06-16 05:07:56

发行:

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

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

解决方案:

我认为您应该注意selectPage中的更改,只有在可用时才进行更新。

代码语言:javascript
复制
React.useEffect(() => {
    if(selectPage) { // <--- check if available
       setPagination(selectPage);
    }
}, [selectPage]); // <--- will run useEffect on everychange of `selectPage`
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62400761

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档