React组件在事件监听器函数中未获取当前状态值

时间:2020-10-19 09:48:50

标签: reactjs redux

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

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

这在基于类的组件中运行正常。您能否分享对此的见识?

对不起,我的英语短。

import cv2

def midpoint(point1, point2):
    # values need to be rounded to an integer to avoid an error when calling cv2.circle() later
    midpoint_x = round((point2[0] + point1[0])/2)
    midpoint_y = round((point2[1] + point1[1])/2)
    midpoint = (midpoint_x, midpoint_y)
    return midpoint

img = cv2.imread('image.jpg')
    
point1 = (352, 92)
point2 = (-2.5121140e+06, 4.8845758e+02)
    
point3 = midpoint(point1, point2)

# starting with radius 10 to make the point initially more visible
img = cv2.circle(img, point3, radius=10, color=(255, 255, 255), thickness=-1)
cv2.imshow("Midpoint position", img)
cv2.waitKey()
cv2.destroyWindow("Midpoint position")

1 个答案:

答案 0 :(得分:1)

以下是根据我的评论实施的示例:

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>