假设数据已经缓存在sessionStorage中。我在外部 CacheService.js 文件中有 HydrateStateWithSessionStorage 。我导入这个文件。当我尝试将 this.setState 传递给此函数时,出现此错误:
未捕获类型错误:无法读取未定义的属性“更新程序”
我该如何解决这个问题?我可以使用 React hook 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 })
});
}
最佳答案
如果没有返回未定义的内容,我会将此函数更多地视为检查返回 sessionStorage 对象。将 this.state 发送到 fn() 然后检查响应并返回响应。
componentDidMount() {
const newState = hydrateState(this.state):
!!newState && this.setState(newState)
}
只是一个脑残..
关于javascript - 将 React 类组件中的 setState 传递给外部函数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56402765/