我尝试在子组件中设置一个回调,但是当调用此回调函数时,状态不会更新,即处于初始状态。
这是为什么以及如何解决此问题?
// calback
const resizeColumn = useCallback(nextWidth => {
console.log(columns); // log empty array, that is initial value why!?
}, [columns]);
function initColumns(newColumns: Array<IColumn>) {
return newColumns.map((item, idx) => {
const column: IColumn = {...item, ...(props.columnsConfig[item.key] || {})};
if (!column.hasOwnProperty("sorter") && props.sortable && !column.sorter)
column.sorter = Boolean(props.onChangeSort) || sorter;
column.title = t(column.title);
column.render = renderCell(column);
column.required = Boolean(column.fixed);
column.width = props.defaultColumnWidth;
column.translateData = props.translateDataSource;
column.onHeaderCell = column => ({
column,
onResize: nextWidth => resizeColumn(nextWidth) //
}); // set callback to child
return column;
}).sort((a, b) => +Boolean(b.fixed) - +Boolean(a.fixed));
}