reactjs - React 组件在事件监听器函数中无法获取当前状态值

标签 reactjs redux

我在安装 TabularListPgination 组件时附加了一个事件监听器。

然后,我尝试在事件监听器中访问当前的 Redux 状态。但是,我得到的是 dataTable reducer 的初始状态而不是当前状态。

这在基于类的组件中运行良好。您能分享一下您对此的见解吗?

抱歉我的英语不好。

import React, { useState, useEffect, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import Paginate from "react-paginate";
import { loadDataTable } from "../../actions/index";

const TabularListPagination = () => {
    const dispatch = useDispatch();
    const dataTable = useSelector((state) => state.dataTable);

    useEffect(() => {
        attachShortcutEvent();
    }, []);

    const attachShortcutEvent = () => {
        document.addEventListener("keydown", (event) => {
            if (event.altKey && event.key === "ArrowLeft") {
                if (dataTable.current.current_page !== 1) {
                    dispatch(loadDataTable(dataTable.current.current_page - 1));
                }
            } else if (event.altKey && event.key === "ArrowRight") {
                if (dataTable.current.current_page !== dataTable.current.total_pages) {
                    dispatch(loadDataTable(dataTable.current.current_page + 1));
                }
            } else if (event.altKey && event.key === "Home") {
                dispatch(loadDataTable(1));
            } else if (event.altKey && event.key === "End") {
                dispatch(loadDataTable(dataTable.current.total_pages));
            }
        });
    };

    return (
        <Paginate
            containerClassName="pagination"
            forcePage={dataTable.current_page}
            pageCount={dataTable.total_pages}
            marginPagesDisplayed={2}
            pageRangeDisplayed={5}
            onPageChange={({ selected }) => {
                dispatch(loadDataTable(selected + 1));
            }}
            nextLabel="&gt;"
            previousLabel="&lt;"
        />
    );
};

export default TabularListPagination;

最佳答案

这是一个如何根据我的评论实现的示例:

const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const { createSelector } = Reselect;

const initialState = {
  dataTable: {
    current: { total_pages: 10, current_page: 1 },
  },
};
//action types
const GO = 'GO';
const FIRST = 'FIRST';
const LAST = 'LAST';
//action creators
const go = (direction) => ({
  type: GO,
  payload: direction,
});
const first = () => ({ type: FIRST });
const last = () => ({ type: LAST });
const reducer = (state, { type, payload }) => {
  if (type === GO) {
    const current_page =
      state.dataTable.current.current_page + payload;
    if (
      current_page < 1 ||
      current_page > state.dataTable.current.total_pages
    ) {
      return state;
    }
    return {
      ...state,
      dataTable: {
        ...state.dataTable,
        current: {
          ...state.dataTable.current,
          current_page,
        },
      },
    };
  }
  if (type === FIRST || type === LAST) {
    const current_page =
      type === FIRST
        ? 1
        : state.dataTable.current.total_pages;
    return {
      ...state,
      dataTable: {
        ...state.dataTable,
        current: {
          ...state.dataTable.current,
          current_page,
        },
      },
    };
  }
  return state;
};
//selectors
const selectDataTable = (state) => state.dataTable;
const selectCurrentDataTable = createSelector(
  [selectDataTable],
  (table) => table.current
);
//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(() => (next) => (action) =>
      next(action)
    )
  )
);
const App = () => {
  const dispatch = useDispatch();
  const dataTable = useSelector(selectCurrentDataTable);

  const keyUp = React.useCallback(
    (event) => {
      //dispatching the actions are not depending on state
      if (event.altKey && event.key === 'ArrowLeft') {
        dispatch(go(-1));
      } else if (
        event.altKey &&
        event.key === 'ArrowRight'
      ) {
        dispatch(go(1));
      } else if (event.altKey && event.key === 'Home') {
        dispatch(first());
      } else if (event.altKey && event.key === 'End') {
        dispatch(last());
      }
      //only dep is dispatch but that never changes so keyUp is only
      //  created when component mounts. Added to dependency to silence
      //  linter (maybe updated version won't warn about dispatch)
    },
    [dispatch]
  );

  React.useEffect(() => {
    document.addEventListener('keydown', keyUp);
    //remove event listener when component is unmounted
    return () => document.removeEventListener(keyUp);
    //keyUp is a dependency but is only created on mount
  }, [keyUp]);

  return (
    <div>
      current page: {dataTable.current_page}
      total pages: {dataTable.total_pages}
    </div>
  );
};

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/4.0.0/reselect.min.js"></script>
<div id="root"></div>

关于reactjs - React 组件在事件监听器函数中无法获取当前状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64424930/

相关文章:

reactjs - 你应该如何使用 flowtype redux thunk ?

javascript - Redux 返回 promise

reactjs - 从 react 中的高阶组件调用实例方法

javascript - 在 array.map 中添加一个值是否被认为是变异的?

javascript - 如何更改axios url?

reactjs - React Native - (0, _redux.combineReducers) 不是函数

reactjs - 使用 React 和 TypeScript 时如何正确输入 @connect?

css - 将样式组件与从 node_module 导入的 CSS 文件一起使用

Redux:(域数据和)应用程序状态与 UI 状态

reactjs - 导入已连接和已断开连接的组件 React、Redux