gpt4 book ai didi

javascript - 无法在 react 组件中设置状态

转载 作者:行者123 更新时间:2023-11-30 08:19:46 25 4
gpt4 key购买 nike

我有一个 React 组件。我想在此组件中设置将传递给子组件的状态。我收到一个引用错误,我不确定为什么。

export const WidgetToolbar: React.FC<{}> = () => {

this.state = {
targetBox:null,
}

const isOpen = useBehavior(mainStore.isWidgetToolbarOpen);
const themeClass = useBehavior(mainStore.themeClass);

const userDashboards = useBehavior(dashboardStore.userDashboards);

const [filter, setFilter] = useState("");
const [sortOrder, setSortOrder] = useState<SortOrder>("asc");

const userWidgets = useMemo(() => {
let _userWidgets = values(userDashboards.widgets).filter((w) => w.widget.isVisible);

if (sortOrder === "asc") {
_userWidgets.sort((a, b) => a.widget.title.localeCompare(b.widget.title));
} else {
_userWidgets.sort((a, b) => b.widget.title.localeCompare(a.widget.title));
}
if (!isBlank(filter)) {
_userWidgets = _userWidgets.filter((row) => {
return row.widget.title.toLowerCase().includes(filter.toLocaleLowerCase());
});
}
return _userWidgets;
}, [userDashboards, sortOrder, filter]);
...

这是我遇到的错误:

TypeError: Cannot set property 'state' of undefined
at WidgetToolbar (WidgetToolbar.tsx?ba4c:25)
at ProxyFacade (react-hot-loader.development.js?439b:757)

最佳答案

功能组件中没有thisthis.state。使用 useState Hook ,类似于您在下面几行中所做的事情。

export const WidgetToolbar: React.FC<{}> = () => {
const [targetBox, setTargetBox] = useState<null | whateverTheTypeIs>(null);

//...

}

关于javascript - 无法在 react 组件中设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55600591/

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