![](/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.