简体   繁体   English

无法在React组件中设置状态

[英]Can not set a state in a react component

I have a react component. 我有一个反应成分。 I want to set the state within this component that will be passed down to child components. 我想在此组件中设置状态,该状态将向下传递给子组件。 I am getting a reference error to this and I am not sure why. 我对此有参考错误,我不确定为什么。

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]);
    ...

This is the error I am getting: 这是我得到的错误:

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

There's no this or this.state in a functional component. 功能组件中没有thisthis.state Use the useState hook, similar to what you're doing a few lines below. 使用useState挂钩,类似于您在下面的几行中所做的。

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

    //...

}

Functional React Components can't have state. 功能性React组件不能具有状态。 You'd have to use a class-based component in order to have state. 您必须使用基于类的组件才能获得状态。

https://guide.freecodecamp.org/react-native/functional-vs-class-components/ https://guide.freecodecamp.org/react-native/functional-vs-class-components/

You used the hook to "use state" in this function: const [filter, setFilter] = useState(""); 您在该函数中使用了挂钩来“使用状态”: const [filter, setFilter] = useState("");

You could do the same for targetBox , instead of trying to set a property on a non-existent 'this' 您可以对targetBox进行相同的操作,而不是尝试在不存在的“ this”上设置属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM