gpt4 book ai didi

javascript - 在事件处理程序中使用 this.setState - "this is undefined"

转载 作者:行者123 更新时间:2023-12-01 00:48:19 25 4
gpt4 key购买 nike

我正在帮助另一位开发人员向搜索结果的表格 View 添加分页。我是 ReactJS 新手,但对普通 JavaScript 非常熟悉。我从 ReactJS 类(class)中借用了代码,在家里仅使用 Node 作为服务器就可以正常工作。在工作中,我们使用 Node、Next 和 PM2。

我正在从 onClick 事件调用事件处理程序。事件处理程序(见下文)调用 this.setState,但单击时出现错误:类型错误:这是未定义的

我尝试过箭头函数和普通函数。普通函数抛出“未定义”错误,箭头函数抛出编译错误:“eventHandler未定义”。我在这里搜索并进行了谷歌搜索,但找不到这个问题的解决方案。该组件中没有类,只有一些 const

function handlePageChange(page){
this.setState((page)=>({currentPage: page}));
}
const Pagination = (props)=>{
const {itemsCount, pageSize}=props;
const pagesCount = Math.ceil(itemsCount / pageSize);
if (pagesCount===1) return null;
let active =1;
const pages = _.range(1,pagesCount+1);
return (
<nav>
<ul className="pagination">
{pages.map(page=>(
<li key={page} active={page===active}>
<a onClick={()=>handlePageChange(page)}>
{page}
</a>
</li>
))}
</ul>
</nav>
)
}

Const Demo = (props)=>{
return (
// ... div, container, table, then the pagination:
<Pagination
itemsCount={props.data.length}
pageSize={pageSize}
currentPage={page}
/>
)}
async function getInitialProps(){}
export default Demo

返回搜索结果时分页显示正确。例如,如果有两页结果,我会得到 1 和 2。但是当我单击任一数字时,我收到 TypeError: this is undefined on the this.setState line。

最佳答案

状态必须是函数/类的一部分,这样会容易得多 reading the main concepts然后一路谷歌搜索找到解决方案。

class Pagination extends React.Component {
state = {
currentPage: 0
};

handlePageChange = page => {
this.setState({ currentPage: page });
};

render() {
const { itemsCount, pageSize } = this.props;
const pagesCount = Math.ceil(itemsCount / pageSize);
if (pagesCount === 1) return null;
let active = 1;
const pages = _.range(1, pagesCount + 1);
return (
<nav>
<ul className="pagination">
{pages.map(page => (
<li key={page} active={page === active}>
<a onClick={() => this.handlePageChange(page)}>{page}</a>
</li>
))}
</ul>
</nav>
);
}
}

关于javascript - 在事件处理程序中使用 this.setState - "this is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57207193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com