gpt4 book ai didi

reactjs - 尝试在函数组件之外调用 useContext

转载 作者:行者123 更新时间:2023-12-04 17:31:52 25 4
gpt4 key购买 nike

我试图弄清楚如何正确使用 React Context。我对尝试从函数组件外部访问 Context 的问题感到困惑。我收到错误:

Line 9:18: React Hook "useContext" is called in function "onDragEnd" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks



这是我的整个 Schedule js 文件:
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { DragDropContext } from 'react-beautiful-dnd';
import OrderColumn from '../ordercolumn/OrderColumn';
import { ScheduleContext } from '../../schedule-context';

const onDragEnd = (result) => {
const { destination, source, draggableId } = result;
const context = useContext(ScheduleContext); // <-- issue is here

if (!destination) {
return;
}

if (
destination.droppableId === source.droppableId &&
destination.index === source.index
) {
return;
}

const column = context.columns[source.droppableId];
const orderIDs = Array.from(column.orderIDs);
orderIDs.splice(source.index, 1);
orderIDs.splice(destination.index, 0, draggableId);

const newColumn = {
...column,
orderIDs: orderIDs
};

const newColumns = {
...context.columns,
newColumn
};

context.setColumns(newColumns);
};

const Schedule = () => {
const { orders, setOrders, columns, setColumns } = useContext(
ScheduleContext
);
return (
<DragDropContext onDragEnd={onDragEnd}>
<div className={'full-width'}>
<h1 className={'text-center'}>Schedule</h1>
<div className={'lines row no-gutters'}>
{columns.map(function(val, index) {
if (index === 0) {
return (
<OrderColumn
title={val.title}
columnId={index}
orders={orders}
setOrders={setOrders}
setColumns={setColumns}
/>
);
} else {
return (
<OrderColumn
title={val.title}
columnId={index}
setOrders={setOrders}
setColumns={setColumns}
/>
);
}
})}
</div>
</div>
</DragDropContext>
);
};

Schedule.propTypes = {
orders: PropTypes.array
};

export default Schedule;

最佳答案

不要听起来油腔滑调,但本质上它的意思正是它所说的。 onDragEnd不是 React 组件,因为它没有返回 ReactElement或某种 JSX。如果您编辑了空白的 return 语句以返回 <div>的(对于所有路径)它将被视为一个组件并正常工作,但截至目前它没有返回任何内容。

关于reactjs - 尝试在函数组件之外调用 useContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866465/

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