简体   繁体   English

如何在 React 中更新/重新渲染列表?

[英]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."我曾尝试使用 useState (这是注释掉的行的来源),但我会收到“重新渲染太多”的错误。 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.我也尝试使用 UseState 但它一直出错。 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.此处的代码应该在按下箭头时更新日历日,但即使更新了 list[],list.map 也不会在 render() 中再次调用来更新它。

    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.请尝试像这样在 React 中编写代码。

So the first problem that comes to the eye is that instead of useEffect, you used onload.所以首先映入眼帘的问题是你使用了onload而不是useEffect。 Try to use useEffect in React.尝试在 React 中使用 useEffect。

The second issue is, using querySelectors where you should be assigning functions as the code shows.第二个问题是,使用 querySelectors 应该在其中分配函数,如代码所示。 Thats the beauty of JSX.这就是 JSX 的美妙之处。

The third major problem is when you say var list = [];第三个主要问题是当你说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.因此,如果您希望 state 或变量在渲染过程中保持不变并且您可以对其进行操作,请使用 useState 或 useRef。

The fourth minor problem is, try switching from var to const or let.第四个小问题是,尝试从 var 切换到 const 或 let。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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