![](/img/trans.png)
[英]How to change useState's state without re-rendering the component, but just its components
[英]How to update a state without re-rendering using useState hook
我有一个 function onCondChange
,只要用户更改TextField
中的值,就会调用它。
const onCondChange = (conds) => {
updateState({
...state,
a: { ...state.a, conds },
b: ++state.b,
})
}
在这里,我在 a 中添加 conds object,类似这样
"a": {
"status": "ACTIVE",
"conds": "{\"rules... (something)..."}"
}
这是 useState 钩子:-
const [state, updateState] = useState({
temp: false,
temp2: true,
a: {
status: test ? '' : ACTIVE
},
b: 0,
});
问题是,每当我更改 TextField 中的值时,都会调用onCondChange
,它会创建另一个重复的 object 并通过在其中添加conds
来更新a
。 这使得重新渲染我想要停止的组件。 我应该如何在不重新渲染的情况下添加conds
object? 问题是 TextField 由于重新渲染而失去了焦点。 当我评论a: {...state.a, conds }
时,焦点并没有丢失,但是我无法在a
中添加conds
object
如果您的问题是失去文本字段的焦点而不是重新渲染。 然后你可以使用useRef()
钩子来设置焦点。 单击此处https://reactjs.org/docs/hooks-reference.html#useref了解更多信息。
function TextField() {
const inputRef = useRef(null);
// you must give dependacy array to useEffect.
useEffect(()=>{
inputRef.current.focus();
})
return (
<>
<input ref={inputRef} type="text" />
</>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.