简体   繁体   中英

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. Use the useState hook, similar to what you're doing a few lines below.

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

    //...

}

Functional React Components can't have state. You'd have to use a class-based component in order to have state.

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

You used the hook to "use state" in this function: const [filter, setFilter] = useState("");

You could do the same for targetBox , instead of trying to set a property on a non-existent 'this'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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