简体   繁体   中英

“Set” method in React Hooks is not working

I'm trying to set a state which contains the current year and the 4 years before it, but for some reason I'm not being able to set the state properly.

const [years, setYears] = useState({ selected: 0, availables: [] })

const getYears = () => {
  const y = {
    selected: new Date().getFullYear(),
    availables: [],
  }
  for (var i = 0; i < 5; i++) {
    y.availables.push(y.selected - i)
  }

  setYears(y)
}

useEffect(() => {
  getYears()
}, [])

In the end, the "years" state stays with its initial values ( {selected: 0, availables: []} ).

Can anyone please help me find out what I'm doing wrong?

You can always simplify your logic by separating the states into selectedYear (number) and availableYears (array). But if you're intent on keeping them contained within a single object, then take a look at the example shown below. Click the Run code snippet button for a working example.

 // current year const currentYear = new Date().getFullYear(); // creates an array of available years where "num" represents // the amount to create/subtract from "year" const createAvailableYears = (num, year) => [...Array(num).fill().map((_, key) => year - key - 1) ]; function App() { const [years, setYears] = React.useState({ selected: currentYear, available: createAvailableYears(4, currentYear) }); const handleChange = React.useCallback(({ target: { value } }) => { setYears({ // updates the selected year selected: value, // sets the available years to: [selected year - 4 years] available: createAvailableYears(4, value) }); }, []); return ( <div className="app"> <select className="select" onChange={handleChange} value={years.selected}> {createAvailableYears(10, 2021).map(year => ( <option key={year} value={year}> {year} </option> ))} </select> <h1>Selected year: {years.selected}</h1> <h3>Available years: {years.available.join(", ")}</h3> </div> ); } // Render it ReactDOM.render( <App />, document.getElementById("react") );
 .app { font-family: sans-serif; text-align: center; }.select { cursor: pointer; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="react"></div>

const [years, setYears] = useState({ selected: 0, availables: [] });
const getYears = () => {
  const tempSelected = new Date().getFullYear();
  let tempAvailables = [];
  for (var i = 0; i < 5; i++) {
    tempAvailables.push(tempSelected - i);
  }

  setYears({ selected: tempSelected, availables: tempAvailables });
};
useEffect(() => {
  getYears();
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM