在 React 组件中将具有内部状态的对象作为实例属性是一种不好的做法吗?



在React 组件中将具有内部状态的对象作为实例属性是一种不好的做法吗?

例如

class PageCacher {
constructor(fetchMethod) {
this.fetchMethod = fetchMethod
this.pages = []
}
async getPage(page) {
if (this.pages[page]) {
return this.pages[page]
} else {
const result = await this.fetchMethod(page)
this.pages[page] = result
return result
}
}
}
class ItemList extends React.Component {
constructor(props) {
super(props)
this.pageCacher = new PageCacher(props.fetchServiceMethod)
}
hanldeFetchPage = (page) => {
this.pageCacher.getPage(page).then(result => {
this.setState({items: result})
})
}
}

PageCache 将请求的页面存储起来,如果没有进行服务调用,则返回结果(如果存在(。

由于您在构造函数中初始化 pageCacher,因此它只会接收组件挂载时存在的 props。

这意味着如果任何道具发生变化,pageCacher 将不会收到这些更新的道具。

链接到组件构造函数的文档

相关内容

最新更新