in useCallback未更新状态值

时间:2020-03-22 11:42:16

标签: javascript reactjs react-hooks use-effect usecallback

我尝试在子组件中设置一个回调,但是当调用此回调函数时,状态不会更新,即处于初始状态。

这是为什么以及如何解决此问题?

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

set callback to child. screenshot

callback, screenshot

0 个答案:

没有答案