[英]Best way to store non-observable data in a React Stateless Component (with Hooks)
I'm using mobx-react / mobx-react-lite for state management 我正在使用mobx-react / mobx-react-lite进行状态管理
Using classes i can define a non observable idToDelete to store the clicked item id, open a Modal using an observable and when the user clicks "Delete", i know the item to delete. 使用类,我可以定义一个不可观察的idToDelete来存储单击的项目ID,使用可观察的对象打开Modal,并且当用户单击“删除”时,我知道要删除的项目。 The id is "remembered" by the component trough the re-renders
id通过重新渲染的组件被“记住”
class Greeting extends React.Component {
idToDelete = null;
confirmDelete = id => {
this.idToDelete = id;
openConfirm = true;
}
closeModal = () => {
openConfirm = true;
this.idToDelete = null;
}
@observable
openConfirm = false;
render() {
// List of items with delete button
<button onClick=this.confirmDelete(id)>Delete</button>
// Confirm Delete Modal
}
}
But in a stateless component the id will become null (the initialization value) on each re-render. 但是在无状态组件中,每次重新渲染时,id都将为null(初始化值)。
Using useLocalStore hook i can store observable values: 使用useLocalStore钩子,我可以存储可观察的值:
All properties of the returned object will be made observable automatically
返回对象的所有属性将自动变为可观察
But i dont want to re-render just because i am storing/changing the id. 但是我不想仅仅因为我正在存储/更改ID而重新渲染。
Using React.React.createContext / useContext seems like a bit overkill to me (it's kind of private value and it is not relevant outside the component itself) 对我来说,使用React.React.createContext / useContext似乎有点矫kill过正(这是私有值,与组件本身无关)
Is there a "local storage" way to achieve this? 是否有“本地存储”方式来实现这一目标? (without observable convertion)
(没有可观察到的转换)
What are best practices for this situation? 在这种情况下,最佳做法是什么?
You can use the useRef hook to save the value. 您可以使用useRef钩子来保存值。 A change to this value will not trigger a re-render and the value will remain the same across renders unless you override it.
更改此值将不会触发重新渲染,并且该值在整个渲染中将保持不变,除非您覆盖它。
Its also explained in detail here 它也在这里详细解释
Yes!
是! The useRef() Hook isn't just for DOM refs.
useRef()挂钩不仅用于DOM引用。 The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
“ ref”对象是一个通用容器,其当前属性是可变的,并且可以保存任何值,类似于类的实例属性。
eg: 例如:
import { useRef } from 'react';
const idToDelete = useRef("");
confirmDelete = id => {
idToDelete.current = id;
}
closeModal = () => {
idToDelete.current = null;
}
Also mind the catch, you need to use .current
to access the data. 另外请注意,您需要使用
.current
来访问数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.