TypeError: props.pagination не определен - PullRequest
0 голосов
/ 16 июня 2020

Я пытаюсь получить данные страницы, которые поступают из хранилища redux, и передать их в локальное состояние с именем pagination. Это состояние разбивки на страницы далее передается дочернему компоненту. Но проблема в том, что всякий раз, когда я пытаюсь передать состояние redux в локальное состояние, я получаю ошибку undefined. Здесь данные определены, я могу console.log данные, но они задерживаются, поэтому я могу получить ошибку. Я не знаю, как это решить. Я использую функциональный компонент React.

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

Таблица. 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);

iage

Таблица. 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);

1 Ответ

0 голосов
/ 16 июня 2020

Проблема:

Согласно журналу вашей консоли вы изначально получаете selectPage undefined, и вы также устанавливаете значение только для mount

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`
...