简体   繁体   English

显示 json 数组中的下一项

[英]Show next items from json array

I have a components, which shows 3 first images from json array.我有一个组件,它显示了 json 数组中的 3 个第一个图像。 I want to add a button which will replace those first 3 items with next 3 in the same array.我想添加一个按钮,它将用同一数组中的下 3 个替换前 3 个项目。 I guess I'm missing something here我想我在这里遗漏了一些东西

 import React, {Component} from 'react'; import '../App.css'; import ImageList from "./ImageList"; class App extends Component { constructor() { super(); this.state = { images: [], index: 0 }; this.toNext = this.toNext.bind(this); } componentDidMount() { fetch("https://picsum.photos/v2/list") .then(res => res.json()) .then(data => { this.setState({ images: data }); }) .catch(err => { console.log('Error happened during fetching!', err); }); } toNext = () => { this.setState({index: (this.state.index + 3)}); } render() { return ( <div className="container"> <h2 className="title">Images list</h2> <ImageList data={this.state.images}/> <button onClick={this.toNext} className="next-btn">Next</button> </div> ) } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.0/umd/react-dom.production.min.js"></script>

The index is being updated correctly, but you are not taking that updated value into account.索引正在正确更新,但您没有考虑更新后的值。 This could be achieved by slicing the images collection in the render method:这可以通过在渲染方法中切片图像集合来实现:

render() {
    const minIndex = this.state.index;
    const maxIndex = minIndex + 3;
    return (
        <div className="container">
            <h2 className="title">Images list</h2>
            <ImageList data={this.state.images.slice(minIndex, maxIndex)}/>
            <button onClick={this.toNext} className="next-btn">Next</button>
        </div>
    )
}

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

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