最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - create useState in a loop based on array possible? - Stack Overflow

programmeradmin2浏览0评论
    const columns = ['task', 'category'];

    for (const text in columns) {
        const [text, setText] = useState();
    }

I wish to create multiple useState things using a loop but to join things together seem to be a problem. What I want it to do is to create consts: task, setTask | category, setCategory

    const columns = ['task', 'category'];

    for (const text in columns) {
        const [text, setText] = useState();
    }

I wish to create multiple useState things using a loop but to join things together seem to be a problem. What I want it to do is to create consts: task, setTask | category, setCategory

Share Improve this question asked Dec 19, 2019 at 19:39 Sander CokartSander Cokart 911 gold badge1 silver badge5 bronze badges 4
  • 6 What I'm seeing here is an XY problem. Using useState in a loop is never the solution, but without explaining the goal behind your question, we can't really help more than saying not to do this. – Emile Bergeron Commented Dec 19, 2019 at 19:43
  • Thats definetely not the right way, as already mentioned. You have to provide more information, so we can give you some guidance. – oemera Commented Dec 19, 2019 at 19:52
  • 1 Does this answer your question? Why can't React Hooks be called inside loops or nested function? – Emile Bergeron Commented Dec 19, 2019 at 20:22
  • 1 @EmileBergeron Thanks for finding and sharing the answer. It worked perfectly for me and resolved a critical issue. – Vivek Goel Commented Jul 7, 2020 at 17:08
Add a comment  | 

5 Answers 5

Reset to default 6

Check this out: https://reactjs.org/docs/hooks-rules.html

Explicitly mentions:

Only Call Hooks at the Top Level Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, 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. (If you’re curious, we’ll explain this in depth below.)

const [text, setText] = ... is just a deconstructing assignment, you can store the result of useState(..) (an array with two elements) however you want, for example:

const columns = ['task', 'category'];
const state = {};

for (const prop of columns) {
  const resultArr = useState();
  state[prop] = {
    val: resultArr[0],
    fn: resultArr[1]
  };
}

And you can use the results like this:

<button onClick={() => state.task.fn('new value')}>{state.task.val}</button>

But as @EmileBergeron mentioned, there doesn't seem to be any reason to use useState like this. There is definitely a more conventional way of solving the problem that you're facing.

Under the hood, useState relies on a linked-list-type nested data structure in the fiber. Each time you call useState that structure is "unwrapped" to get the data associated with the next hook call.

This is a good article that goes into depth about how hooks work.

In theory, so long as your loop always executes the same number of times, you could use a hook inside of the loop. HOWEVER, as other people have said here, this is not a standard way of doing things and is not advisable.

const columns = ['task', 'category'];
columns.map( (column, index) => {
  let col = column;
  let setCol = column+index;
  [col, setCol] = useState(false)
})

This way it will give unique state for each iteration of elements in the array columns

const [uploadAnimal, setAnimal] = useState(['cat']);

const loopFun = () => {
const arr = uploadAnimal
for (let i = 0; i < 10; i++) {
  
   arr.push('DOG')
   setUploadCount([...arr])
} };
发布评论

评论列表(0)

  1. 暂无评论