React - For Loop 条件渲染 - 不工作和无限触发

我正在尝试基于像这样的可变类型在我的渲染中动态地多个项目


<div>

  <Multiple

    multiple={props.multiple}

    base1={props.base1}

    exp1={props.exp1}

  />

</div>


const Multiple = (props) => {

    let result = "";

    let wtf = "";

    console.log("test"); // gets triggered

    for(let i = 0; i < props.multiple; i++){

        console.log("i: "+i); // gets triggered

        result.concat("{props.base1} +"); // this doesn't work for some reason

        wtf = i; // gets triggered

    }

    console.log("result: "+result); // result is blank

    console.log("wtf:" +wtf);

    return <span>{result}</span>;

}

问题 1:即使我进入了 for 循环,我的结果也没有改变,我不明白为什么。


另外因为我还不能让它工作,我想问:如果我这样做,我将 {props.base1} 作为字符串连接起来,当我在渲染中返回它时,它会显示为“{ props.base1}" 还是会呈现为变量值?


这是一个关于它应该是什么样子的例子:


base1 = abc

multiple = 2


resulting render should look like:

abc + abc +

在渲染之前将我的道具连接成一个字符串会导致它看起来像这样而不是上面的块吗?


{props.base1} + {props.base1} +

问题 2:还编辑,由于某种原因,<Multiple>组件中的所有内容都在无限触发,我也不明白为什么会这样


拉丁的传说
浏览 88回答 3
3回答

芜湖不芜

您正在使用 concat,它不会更新原始字符串,而是创建一个新字符串。你可以做的是let result = '';for(let i = 0; i < props.multiple; i++) {&nbsp; console.log("i: "+i); // gets triggered&nbsp; result += `${props.base1} `;&nbsp;&nbsp; wtf = i; // gets triggered}console.log(result);就无限循环问题而言,究竟是什么props.muitlple?是数组还是字符串?如果是这样,您应该将循环更改为for(let i = 0; i < props.multiple.length; i++)编辑:如果 props.multiple 是一个数字,i < props.multiple应该可以工作,您应该在组件中记录该值并检查一次。

holdtom

结果字符串未正确附加到const Multiple = (props) => {&nbsp; &nbsp; let result = "";&nbsp; &nbsp; let wtf = "";&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for(let i = 0; i < props.multiple; i++){&nbsp; &nbsp; &nbsp; &nbsp; result += props.base1.toString() + "+"&nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; console.log("result: "+result);&nbsp;&nbsp; &nbsp; return <span>{result}</span>;}对于无限循环,我会在进入循环之前检查它的值,以确保您的边界设置正确。// add this line before for loopconsole.log(props.multiple)

慕的地10843

A。更改为result.concat('${props.base1} + ');(后背!!)b.&nbsp;我认为你传递给的道具可能有问题<Multiple ... >。再次检查它们的值,也许记录它们的值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript