[英]What's the best way to store a global variable for a reusable React component?
I'm building a React component (think a button) that makes a network request when clicked.我正在构建一个 React 组件(想想一个按钮),它在点击时发出网络请求。 This component may be rendered multiple times on the same page, but the network request only needs to happen once.
这个组件可以在同一个页面上多次渲染,但是网络请求只需要发生一次。 Therefore, I want to store a variable,
networkRequestWasMade
, to check against before making the request.因此,我想存储一个变量
networkRequestWasMade
,以便在发出请求之前进行检查。
Normally, I'd find a common parent and wrap it in React's context mechanism.通常,我会找到一个共同的父级并将其包装在 React 的上下文机制中。 But, this component will be part of a reusable component library that will be used across many applications (think hundreds), so I would prefer that it doesn't rely on a specific parent component or context to store this value.
但是,这个组件将成为一个可重用组件库的一部分,该库将在许多应用程序(想想数百个)中使用,所以我希望它不依赖于特定的父组件或上下文来存储这个值。 I am brainstorming about what would be the best way to achieve this.
我正在集思广益什么是实现这一目标的最佳方式。
A very simple solution would be to attach a boolean to the window
object:一个非常简单的解决方案是将布尔值附加到
window
对象:
function Button() {
const handleClick = () => {
if (!window.networkRequestWasMade) {
// ...make request...
window.networkRequestWasMade = true
}
}
return <button onClick={handleClick}>Click me!</button>
}
However, I'm wondering if there's a better pattern for this.但是,我想知道是否有更好的模式。
Try to not use global variables, this is a bad practice.尽量不要使用全局变量,这是一个不好的做法。 You just need to store the promise into a variable and initialize it only the very first time.
您只需要将承诺存储到一个变量中并仅在第一次初始化它。
Here is an example using axios to make the http call这是一个使用axios进行 http 调用的示例
// util.js
let p;
function loadData() {
if (!p) {
p = axios.get('uri')
.then(response => result = response.data);
}
return p;
}
Then your component can call the function loadData
multiple times, the http call will be executed only once那么你的组件可以多次调用
loadData
函数,http 调用只会执行一次
// Button.jsx
import { loadData } from './util'
function Button() {
const handleClick = () => {
loadData()
.then(data => {
// do what you want with the data
})
}
return <button onClick={handleClick}>Click me!</button>
}
Maybe the http request is not a GET
and you don't care about the result but you get the idea.也许 http 请求不是
GET
,您不关心结果,但您明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.