简体   繁体   中英

How can I update / re-render a list in React?

I have tried using useState (which is what the commented out lines are from) but I would get an error of "too many re-renders." The list updates correctly but the component is not updated on the screen. I can't figure out how to get react to update the data in render though. I also tried using UseState but it kept erroring out. I am new to react so i'm kind of lost on how to do this.

The code here is supposed to update the calendar days when the arrows are pressed but even though the list[] is updated, list.map isn't called again in render() to update this.

    function App() {

  var currentMonth = 0;
  var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  var monthNames = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  //const [list, updateList] = useState([]);
  var list = [];

  var monthName;
  //var copyList

  const startCalender = (month) => {

    //copyList = [];
    list = [];
    monthName = monthNames[month];

    for (let day = 0; day < months[month]; day++) {
      //copyList.push(<div>Day: {day + 1}</div>
      list.push(<div>Day: {day + 1}</div>
      )}}

      //updateList(copyList);

  startCalender(currentMonth);

  const changeMonth = (changeAmount) => {
    currentMonth += changeAmount;

    if(currentMonth > 11) currentMonth = 0
    else if(currentMonth < 0) currentMonth = 12;

    console.log("here1");

    startCalender(currentMonth);
  }

  const initalizeVariables = () => {
     document.querySelector(".leftArrow").addEventListener('click', () => {
       changeMonth(-1);
     });
     document.querySelector(".rightArrow").addEventListener('click', () => {
       changeMonth(1);
     });
  }

  window.onload = initalizeVariables;
   
  return (
    <div className="App">
      <div className="header">
        <BiLeftArrowAlt className="arrowIcon leftArrow"/>
        <div>{monthName}</div>
        <BiRightArrowAlt className="arrowIcon rightArrow"/>
      </div>
      <div className = "daysContainer">
        {list.map((data) => {
          return <IndividualDay info={data}/>
        })}
      </div>
    </div>
  );
}

Try this:

 export default function App() { const months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; const monthNames = [ "January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; const [theList, setTheList] = useState([]); const [currentMonth, setCurrentMonth] = useState(0); let monthName; //var copyList const startCalender = (month) => { const list = []; monthName = monthNames[month]; for (let day = 0; day < months[month]; day++) { //copyList.push(<div>Day: {day + 1}</div> list.push(<div>Day: {day + 1}</div>); } setTheList(list); }; const changeMonth = (changeAmount) => { let theCurrentMonth = currentMonth; theCurrentMonth += changeAmount; if (theCurrentMonth > 11) theCurrentMonth = 0; else if (theCurrentMonth < 0) theCurrentMonth = 12; setCurrentMonth( theCurrentMonth ); startCalender(theCurrentMonth); }; useEffect(() => { startCalender(currentMonth); }, []); return ( <div className="App"> <div className="header"> <div onClick={() => changeMonth(-1)}> <BiLeftArrowAlt className="arrowIcon leftArrow"/> </div> <div>{monthName}</div> <div onClick={() => changeMonth(1)}> <BiRightArrowAlt className="arrowIcon leftArrow"/> </div> </div> <div className="daysContainer"> {theList.map((data) => { return <IndividualDay info={data}/>; })} </div> </div> ); }

Please try to code in React like so as well.

So the first problem that comes to the eye is that instead of useEffect, you used onload. Try to use useEffect in React.

The second issue is, using querySelectors where you should be assigning functions as the code shows. Thats the beauty of JSX.

The third major problem is when you say var list = []; in the code, your basically redoing this line every render. So if you want a state or variable to stay constant through renders and which you can manipulate, use useState or useRef.

The fourth minor problem is, try switching from var to const or let.

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