简体   繁体   English

如何将组件存储在数组中并在需要时在 React 中渲染它们?

[英]How to store components in an array and render them when I need in React?

I want to render x numbers times a specific component according to what the user chooses.我想根据用户的选择将 x 个数字乘以特定组件。

I wrote this function:我写了这个 function:

const generateShiftsForm = (totalWeeks) => {
        const shiftWeeks = 1;
        const shiftList = [];
        for (let i = shiftWeeks; i === totalWeeks; i++) {
          shiftList.push(<ShiftForm totalMinutes={totalMinutes} setTotalMinutes={setTotalMinutes}/>);
        }
        return shiftList;
      };

But when I call it inside the render function it doesn't generate anything unless the totalWeeks is 1.但是当我在渲染 function 中调用它时,除非totalWeeks为 1,否则它不会生成任何内容。

  {generateShiftsForm(shiftNumber).map((form) => (form))}

Why is it like this?为什么会这样? I didn't get it, can someone explain it to me?没看懂,谁能解释一下?

Seems like there is a typo in the for loop condition - i === totalWeeks , that's why the for loop is being run only once and only if totalWeeks equals 1. Try replacing the for loop you have with the following:似乎 for 循环条件中有一个错字 - i === totalWeeks ,这就是为什么 for 循环只运行一次并且只有当totalWeeks等于 1 时。尝试用以下内容替换你的 for 循环:

for (let i = shiftWeeks; i <= totalWeeks; i++) {...}

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

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