Loop inside of a loop, in React JSX

天涯浪子 提交于 2019-12-14 02:09:22

问题


I am trying to render in react, jsx, a loop inside of a loop Like bellow:

{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}        
        {item}
    )
})}

This does not work any other suggestions


回答1:


You forgot the wrapping div in your first map statement:

render() {
  return (
    <div>
      {this.state.ans.map(item =>
        <div> // this div was missing
          {this.state.quest.map(quest => quest)}
          {item}
        </div>
      )}
    </div>
  )
}



回答2:


Try it like this:

render(){
    return (
        .
        .
        .
        {this.state.ans.map((item) => {
            return (
                <div>
                    {this.state.quest.map((item1) => { 
                           return (item1); 
                        }
                    )}        
                   {item}
               </div>
            );
        })}
    );
}

Basically the idea is that, you should return a single element - in my example a div (with the latest react version you don't have to). And moreover, use lambdas in order for this to reference the correct context.

If you do not use ES6, you can add the following statement at the beginning of the render method:

var that = this;

and use that afterwards with the function(){} syntax inside the return.



来源:https://stackoverflow.com/questions/47632781/loop-inside-of-a-loop-in-react-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!