将 React 类组件中的 setState 传递给外部函数时出错



>假设数据已经缓存在sessionStorage中。我在外部 CacheService.js 文件中有 hydrateStateWithSessionStorage。我导入此文件。当我尝试将 this.setState 传递给此函数时,出现此错误:

捕获的类型错误:无法读取未定义的属性"更新程序">

我该如何解决这个问题?我可以使用 React 钩子 useState 并传递 setter 函数,但是如果我想使用类组件而不是函数组件怎么办?还是我根本无法传递 setState,因为它在实现中隐式使用了"this"关键字?

   hydrateStateWithSessionStorage(state, setState) {
    // for all items in state
    for (let key in state) {
        // if the key exists in localStorage
        if (sessionStorage.hasOwnProperty(key)) {
            // get the key's value from localStorage
            let value = sessionStorage.getItem(key);
            // console.log(value)
            // parse the localStorage string and setState
            try {
                value = JSON.parse(value);
                console.log('before')
                setState({ [key]: value });
                console.log('after')
            } catch (e) {
                // handle empty string
                setState({ [key]: value });
            }
        }
    }
}

//in the component consuming CacheService
//this.Cache = new CacheService(); //in the constructor
componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this.state, this.setState);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}
如果

没有任何返回未定义的内容,我会将这个函数视为检查返回会话存储对象。将 this.state 发送到 fn(( 中,然后检查响应并返回响应。

componentDidMount() {
 const newState = hydrateState(this.state):
 !!newState && this.setState(newState)
}

只是一个大脑转储..

这个怎么样?

componentDidMount() {
    this.Cache.hydrateStateWithLocalStorage(this);
    this.Auth.fetch('api/upcomingbill/').then((data) => {
        this.setState({ list: data })
    });
}

然后像这样使用设置状态...

hydrateStateWithSessionStorage(ReactComp) {
    for (let key in ReactComp.state) {
        ...
        ReactComp.setState({ [key]: value });
        ....
    }
}

仅供参考,这不是 React 的具体问题。您收到该错误的原因是,您只将一个内部使用"this"(该特定类(的方法传递给 hydrateStateWithSessionStorage 函数。到在函数中调用该方法时,范围已更改,并且"this"未定义或不再相同。

最新更新