React hooks useState Array

前端 未结 5 1201
眼角桃花
眼角桃花 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:08

    You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect for this.

    The following version works:

    import React, { useState, useEffect } from "react";
    import ReactDOM from "react-dom";
    
    const StateSelector = () => {
      const initialValue = [
        { id: 0, value: " --- Select a State ---" }];
    
      const allowedState = [
        { id: 1, value: "Alabama" },
        { id: 2, value: "Georgia" },
        { id: 3, value: "Tennessee" }
      ];
    
      const [stateOptions, setStateValues] = useState(initialValue);
      // initialValue.push(...allowedState);
    
      console.log(initialValue.length);
      // ****** BEGINNING OF CHANGE ******
      useEffect(() => {
        // Should not ever set state during rendering, so do this in useEffect instead.
        setStateValues(allowedState);
      }, []);
      // ****** END OF CHANGE ******
    
      return (
    ); }; const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);

    and here it is in a code sandbox.

    I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState directly without using useState at all). If so, that api call to load the list could also go inside the useEffect block.

提交回复
热议问题