React hooks useState Array

前端 未结 5 1139
眼角桃花
眼角桃花 2021-01-30 07:39

I tried looking for resetting useState array values in here but could not find any references to array values.

Trying to change the drop down value from ini

5条回答
  •  时光说笑
    2021-01-30 08:07

    To expand on Ryan's answer:

    Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

    React docs:

    setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

    Essentially, you're setting state with:

    setStateValues(allowedState);
    

    causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

    To illustrate the point, if you set a timeout as like:

      setTimeout(
        () => setStateValues(allowedState),
        1000
      )
    

    Which ends the 'too many re-renders' issue.

    In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

提交回复
热议问题