[英]React: Is there any way to cache components or prevent redundant HTTP calls with each render
The simple Code Sandbox below shows that navigating to a component triggers a fresh render.下面的简单代码沙箱显示导航到组件会触发新的渲染。 The React profiler states the components were rendered because they are continually seen for the first time.
React 分析器指出组件已被渲染,因为它们是第一次连续出现。 I understand this to be the correct React behavior, because each mounting/render generates new method references that triggers the re-rendering.
我理解这是正确的 React 行为,因为每个安装/渲染都会生成触发重新渲染的新方法引用。 However, this means that several http requests will be made despite nothing having changed.
然而,这意味着尽管没有任何改变,但仍会发出几个 http 请求。 Is there any way to keep those requests from being made every time the user navigates to a component?
有什么方法可以防止每次用户导航到组件时都发出这些请求?
In the codesandbox
I've tried using React.memo
along with useCallback
, and neither reuse the initial rendering.在
codesandbox
,我尝试使用React.memo
和useCallback
,并且都没有重用初始渲染。
Click the console
tab to see each time the component renders, it makes a fresh ajax call.单击
console
选项卡以查看每次组件呈现时,它都会进行新的 ajax 调用。
https://codesandbox.io/s/github/pstephenwille/react-render-question https://codesandbox.io/s/github/pstephenwille/react-render-question
To avoid redundant HTTP calls you have to verify that your origin server does not have updated your local data.为了避免多余的 HTTP 调用,您必须验证您的源服务器没有更新您的本地数据。 If you really want to just fire the HTTP calls once, you can eg execute them in your
App
component or pass a state and a callback function down to your Foo
and Bar
screen components that will ensure a singular call如果你真的只想触发一次 HTTP 调用,你可以在你的
App
组件中执行它们,或者传递一个 state 和一个回调 function 来确保你的Foo
和Bar
组件调用单一的屏幕组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.