简体   繁体   English

如何在反应js中增加map function

[英]How to do increment in map function in react js

`{Array.apply(null, {length:this.state.length}).map((value, i) => ( 
<div>
<div>{i}</div>
<div>{i+1}</div>
<div>{i+2}</div>
</div>)}
<button onClick={()=>this.loadmore(event)}>Load More</button>`

Below is the load more code下面是加载更多代码

public loadmore(e)
{
  e.preventDefault()
  this.setState(prevState => ({length:prevState.length+1}))
}

I want to display 012 (when i click load more 456 should appear) 345 678我想显示 012 (当我点击加载更多 456 应该出现) 345 678

Instead I'm getting 012 123 234相反,我得到的是 012 123 234

Is there any way to increment the value of i after i+2有没有办法在 i+2 之后增加 i 的值

In your callback, i is the index of the entry ( 0 for the first entry, 1 for the second, etc.), so if you're outputting three items per entry and you want to start counting from 1, the three items will be i * 3 + 1 , i * 3 + 2 , and i * 3 + 3 :在您的回调中, i是条目的索引(第一个条目为0 ,第二个条目为1 ,等等),因此如果您要为每个条目输出三个项目并且您想从 1 开始计数,则这三个项目将是i * 3 + 1i * 3 + 2i * 3 + 3

Array.from({length: this.state.length}).map((value, i) => {
    i *= 3;
    return (
        <div>
            <div>{i + 1}</div>
            <div>{i + 2}</div>
            <div>{i + 3}</div>
        </div>
    );
})

(Or each div could be <div>{++i}</div> .) (或者每个 div 可以是<div>{++i}</div> 。)

Live Example:现场示例:

 class Example extends React.Component { constructor(props) { super(props); this.state = {length: 1}; this.loadmore = this.loadmore.bind(this); } loadmore() { this.setState(({length}) => ({length: length + 1})); } render() { const {length} = this.state; const divs = Array.from({length: this.state.length}).map((value, i) => { i *= 3; return ( <div> <div>{i + 1}</div> <div>{i + 2}</div> <div>{i + 3}</div> </div> ); }); return ( <div> {divs} <input type="button" onClick={this.loadmore} value="Load More" /> </div> ); } } ReactDOM.render(<Example/>, document.getElementById("root"));
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>

I changed a couple of other things in the live example:我在现场示例中更改了其他一些内容:

  • You can use destructuring to make your setState call a bit more concise if you like:如果您愿意,可以使用解构使您的setState调用更简洁:

     this.setState(({length}) => ({length: length + 1}));
  • I bound loadmore in the constructor rather than recreating a function on every render in onClick .我在构造函数中绑定了loadmore ,而不是在 onClick 的每个渲染上onClick
  • You had a typo in your JSX, missing / on the closing </div> tags你的 JSX 中有错字,在结束</div>标记上缺少/

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

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