gpt4 book ai didi

reactjs - 使用react-redux转发功能组件中的ref(v.6.0.1)

转载 作者:行者123 更新时间:2023-12-03 13:59:39 24 4
gpt4 key购买 nike

我正在尝试在我的功能组件中使用 forwardRef,该组件也使用 react-redux。我的组件如下所示:

const InfiniteTable = ({
columns,
url,
data,
stateKey,
loading,
loadMore,
fetchData,
customRecordParams,
...rest
}, ref) => {
const [start, setStart] = useState(0);
const tableRef = React.createRef();

console.log(rest);

let dataSource = data;
if (customRecordParams) dataSource = _.map(dataSource, customRecordParams);
if (dataSource.length > FETCH_LIMIT)
dataSource = _.slice(dataSource, 0, start + FETCH_LIMIT);

useEffect(() => setupScroll(setStart, tableRef), []);
useEffect(() => {
if (loadMore) fetchData(url, stateKey, { start });
}, [start, loadMore]);

useImperativeHandle(ref, () => ({
handleSearch: term => console.log(term),
handleReset: () => console.log("reset")
}));

return (
<Table
columns={columns}
dataSource={dataSource}
pagination={false}
showHeader
loading={loading}
/>
);
};

const mapStateToProps = (state, ownProps) => ({
data: Object.values(state[ownProps.stateKey].data),
loading: state[ownProps.stateKey].isFetching,
loadMore: state[ownProps.stateKey].loadMore
});

export default connect(
mapStateToProps,
{ fetchData },
null,
{ forwardRef: true }
)(InfiniteTable);

但是,当我尝试将我的组件与 ref 属性一起使用时,我收到此错误:

Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

我做错了什么?

最佳答案

InfiniteTable 签名不正确,它是 legacy context它作为功能组件中的第二个参数接收,而不是 ref。为了接收 ref 对象并与 useImperativeHandle 一起使用,组件应该用 React.forwardRef 包装。

the reference州,

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef

应该是:

const InfiniteTable = forwardRef((props, ref) => { ... });

export default connect(
mapStateToProps,
{ fetchData },
null,
{ forwardRef: true }
)(InfiniteTable);

关于reactjs - 使用react-redux转发功能组件中的ref(v.6.0.1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com