Reactjs 如何在客户端缓存react组件?
是否有一种方法可以在客户端缓存react组件。如果用户来到一个页面,说a,然后导航到另一个页面,说B,当他再次回到a时,我希望渲染不执行,不应执行api调用,该页面应从缓存中提供。您可以缓存Reactjs 如何在客户端缓存react组件?,reactjs,Reactjs,是否有一种方法可以在客户端缓存react组件。如果用户来到一个页面,说a,然后导航到另一个页面,说B,当他再次回到a时,我希望渲染不执行,不应执行api调用,该页面应从缓存中提供。您可以缓存状态 let cachedState = null; class ExampleComponent extend React.Component { constructor(props) { super(props); this.state = cachedState
状态
let cachedState = null;
class ExampleComponent extend React.Component {
constructor(props) {
super(props);
this.state = cachedState !== null ? cachedState : {
apiData: null
}
}
componentWillUnmount() {
cachedState = this.state;
}
componentDidMount() {
if (this.state.apiData === null) {
this.loadApiData()
.then(apiData => {
this.setState({apiData});
});
}
}
loadApiData = () => {
// code to load apiData
};
}
这种方法将违反反应生命周期hook@SangramBadi:React在浏览器中生成html,使用这种方法,我们将记录呈现的组件,而不是重新计算这是数据缓存,但我说的是整个页面缓存是可能的。React是数据驱动的,我们应该从数据呈现页面。我认为保存页面状态是最好的方法。