React 自定义钩子:有没有办法动态设置属性?
我有一行标题,我想在其中附加一个 clickHandler 来控制各自列的数据的 ASC
和 DESC
。
我的强力尝试是循环所有标头并创建一个对象,该对象具有一个属性来表示每个标头,并带有一个值,让钩子知道哪个标头处于活动状态或不处于活动状态,即在 ASC
或 中DESC
:
{ 1: false, 2: false, 3: false....}
代码:
function addPropToObj(arr) {
var obj = {}
arr.forEach(o => {
obj[o.id] = false;
})
return obj;
}
const activeObj = addPropToObj(userData)
function useActiveToggle(initialState = activeObj, bool = false) {
const [state, setState] = React.useState(initialState);
const toggle = React.useCallback((id) => {
return setState((previousState) => ({ ...previousState, [id]: !previousState[id] }))
}, [])
return [state, toggle]
}
数组中只有 199 个对象,但如果有 1000 个或 10,000 个呢?
我知道我听说 JS 中的对象很便宜,但感觉不对。
所以我尝试了这个:
function useActiveToggle(initialState = {}, bool = false) {
const [state, setState] = React.useState(initialState);
const toggle = React.useCallback((id) => {
return setState((previousState) => {
if (!previousState[id]) {
previousState = { ...previousState, ...{ [id]: true } }
}
return ({ ...previousState, [id]: !previousState[id] })
})
}, [])
return [state, toggle]
}
但这会导致混乱!奇怪的行为!
我的一部分认为我的蛮力想法可能不太可怕,如果我错了请纠正我,但是如何反应才能在它必须处理的所有和解中做出这样的事情呢?
有人知道如何解决这个问题吗?
I have a row of headers in which I would like to attach a clickHandler to control the ASC
and DESC
of data for their respective column.
My brute force attempt was to loop all the headers and create an object which would have a property to represent each header with a value to let the hook know which is active or not i.e. in ASC
or DESC
:
{ 1: false, 2: false, 3: false....}
The code:
function addPropToObj(arr) {
var obj = {}
arr.forEach(o => {
obj[o.id] = false;
})
return obj;
}
const activeObj = addPropToObj(userData)
function useActiveToggle(initialState = activeObj, bool = false) {
const [state, setState] = React.useState(initialState);
const toggle = React.useCallback((id) => {
return setState((previousState) => ({ ...previousState, [id]: !previousState[id] }))
}, [])
return [state, toggle]
}
They're only 199 objects in the array, but what if there were 1000, or 10,000?
I know I've heard objects are cheap in JS but it doesn't feel right.
So I tried this:
function useActiveToggle(initialState = {}, bool = false) {
const [state, setState] = React.useState(initialState);
const toggle = React.useCallback((id) => {
return setState((previousState) => {
if (!previousState[id]) {
previousState = { ...previousState, ...{ [id]: true } }
}
return ({ ...previousState, [id]: !previousState[id] })
})
}, [])
return [state, toggle]
}
But that results in a mess! Strange behaviors!
A part of me thinks my brute force idea might not be too horrible, correct me if I'm wrong but how could react do something like this with all the reconciliation it has to deal with?
Anyone have an idea how to approach this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是猜测这就是你想要的吗?
Just guessing this is what you want?