問題描述
如何為 useState 創建動態函數名稱? (How do I create a dynamic function name for useState?)
I am trying to add useState
hooks from an array of names, but it doesn't seem to work the way I thought it would work. Does anyone have an idea on how I can achieve this?
let f = {
get: { },
set: { }
};
for (let field of fields) {
const [f.get[field], f.set[field]] = useState(menu[field]);
}
and the error I am getting atm:
imports/ui/admin/Menu.jsx:128:10: /home/csi/csi/imports/ui/admin/Menu.jsx: Unexpected token, expected "," (128:10)
126 | };
127 | for (let field of fields) {
> 128 | const [f.get[field], f.set[field]] = useState(menu[field]);
| ^
129 | }
130 |
131 | const submit = e => {
Thanks in advance!
參考解法
方法 1:
You can use useState inside loops only if you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
See this ans for better clarification Learn Here