React - 函数不打印当前状态

React - function does not print current states

使用 Fluent UI DetailsList,我创建了这个解决方案。我删除了所有不必要的行以尽量减少问题,因为看起来在登录 onColumnClick 时它不打印当前状态而是打印初始状态,为什么会这样:

import * as React from 'react';
export const ClvKkcgListyHistorie = (props: IClvKkcgListyHistorieWebPartProps) => {
const [notifications, setNotifications] = React.useState<INotificationDetailsList[]>([]);
const [columns, setColumns] = React.useState<IColumn[]>();

React.useEffect(() => {
  setColumns(createColumns(onTitleClick, onColumnClick));
}, []);

// With this useEffect everything works fine
React.useEffect(() => {
  setColumns(createColumns(onTitleClick, onColumnClick));
}, [notifications]);

React.useEffect(() => {
  const fetchAllNotifications = async () => {
   // Fetch items here
  }
  fetchAllNotifications();
}, [])


const onColumnClick = (e: any, column: IColumn) => {
  console.log(notifications,columns, "1" ); 
  // Here I get [], undefined, "1"
}

return (
  <>
  {notifications.length !== 0 && 
    <DetailsList 
      items={notifications} 
      columns={columns}
    >
    </DetailsList>
  }
  </>
);
}

Columns.tsx

import * as React from 'react';


export const createColumns = (onTitleClick: any, onColumnClick: any) : IColumn[] => {
  return [
    {
      key: "title", 
      name: "Nadpis", 
      minWidth: 70,
      maxWidth: 100,
      isResizable: true,
      isRowHeader: true,
      isSorted: false,
      isSortedDescending: false,
      sortAscendingAriaLabel: 'A - Z',
      sortDescendingAriaLabel: 'Z - A',
      isPadded: true,
      onColumnClick: onColumnClick,
      onRender: (item: INotificationDetailsList) => {
        return <span>{item.Title}</span>;
      }
    },

    }
  ]
} 

在那

当您呈现组件时,它会创建此函数 onColumnClick 并查看此刻的列。它将那个函数传递给处理程序,记住那些列是什么。 (在您的例子中,是一个空数组。)

为了在列更新时更新函数,您需要使用useCallback。它与 useEffect 的模式类似,但是 returns 一个函数,而不是在依赖项发生变化时运行一个函数。

const onColumnClick = React.useCallback((e: any, column: IColumn) => {
  console.log(notifications,columns, "1" ); 
  // This will return a different function to the handlers
  // whenever columns changes, but not notifications
}, [columns])