我发现了如何实现分页here,它可以在stackblitz上运行,但是当我将代码移到编辑器时,它表明它是未定义的。
这是代码:
import React from "react";
import { PropTypes } from "prop-types";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import {
getPosts,
setKeyword,
getPostsByKeyword
} from "../actions/postsActions";
import PostItem from "./PostItem";
class PostList extends React.Component {
constructor(props) {
super(props);
this.state = {
searchTerm: "",
postsPerPage: 8,
currentPage: 1
};
}
componentDidMount() {
this.props.getPosts();
}
setPage = e => {
this.setState({
currentPage: e.target.id
});
};
onSearchChange = e => {
this.setState({
searchTerm: e.target.value
});
};
filterPosts = () => {
this.props.setKeyword(this.state.searchTerm);
};
render() {
const { postsPerPage, currentPage } = this.state;
const { posts, filtered } = this.props;
if (posts.length > 0) {
const lastPost = currentPage * postsPerPage;
const firstPost = lastPost - postsPerPage;
const currentPosts = posts.slice(firstPost, lastPost);
}
const pages = [];
for (var i = 1; i <= Math.ceil(posts.length / postsPerPage); i++) {
pages.push(i);
}
return (
<div>
<input
type="text"
onChange={this.onSearchChange}
placeholder="Search posts"
id="searchInput"
onKeyUp={this.filterPosts}
value={this.state.searchTerm}
/>
<div className="grid">
{posts && filtered.length < 1
? currentPosts.map(p => {
return <PostItem key={p._id} post={p} />;
})
: filtered.map(f => {
return <PostItem key={f._id} post={f} />;
})}
</div>
{filtered.length < 1 && (
<ul className="pagination">
{pages.map(n => {
return (
<li
className="pagination-item"
id={n}
key={n}
onClick={this.setPage}
>
{n}
</li>
);
})}
</ul>
)}
</div>
);
}
}
PostList.propTypes = {
getPosts: PropTypes.func,
setKeyword: PropTypes.func,
posts: PropTypes.array,
filtered: PropTypes.array
};
const mapStateToProps = state => {
return {
posts: state.posts.posts,
filtered: getPostsByKeyword(state)
};
};
export default withRouter(
connect(
mapStateToProps,
{ getPosts, setKeyword }
)(PostList)
);
是因为它在if
语句中还是什么。我还尝试检查currentPosts
是否与currentPosts && ...
在一起,但结果相同。
您可以在这里看到它,希望它能起作用,我添加了一些硬编码数据:stackblitz