Javascript 在React类组件中执行循环

Javascript 在React类组件中执行循环,javascript,reactjs,Javascript,Reactjs,我正在构建一个分页组件,我正在努力执行for循环,以便动态生成页面。我最初有一个函数组件,但我想将其切换为类组件,以便管理其中的状态。(我知道,我可以使用钩子,但我现在正在练习类组件) 我最初在render方法中添加了for循环,但它执行了两次循环,因为组件ir渲染了两次。然后,我尝试了componentDidMount(),但它没有任何作用。。。然后使用componentWillMount()并成功。然而,我知道这可能是一种不好的做法 有什么想法吗?请参见下面带有componentDidMou

我正在构建一个分页组件,我正在努力执行for循环,以便动态生成页面。我最初有一个函数组件,但我想将其切换为类组件,以便管理其中的状态。(我知道,我可以使用钩子,但我现在正在练习类组件)

我最初在render方法中添加了for循环,但它执行了两次循环,因为组件ir渲染了两次。然后,我尝试了componentDidMount(),但它没有任何作用。。。然后使用componentWillMount()并成功。然而,我知道这可能是一种不好的做法

有什么想法吗?请参见下面带有componentDidMount()的组件

import React,{Component}来自'React';
从“/Pagination.module.css”导入样式;
类分页扩展了组件{
状态={
页码:[],
已选择:“”,
};
componentDidMount(){
为了(
设i=1;
我{
this.setState({selected:number});
};
render(){
返回(
    {this.state.pageNumbers.map((num)=>(
  • ))}
); } } 导出默认分页;
您不应该像这样更新状态:

this.state.pageNumbers.push(i);
这样做:

  this.setState((s) => {
    return {
        ...s,
        pageNumbers: [...s.pageNumbers, i]
    }
})

您最好将所有数字推入
数组
,然后更新
页码
状态。
this.state.pageNumbers.push(i);
不直接更新状态,您需要在计算完成后使用
setState

 componentDidMount() {
  const { pageNumbers = [] } = this.state
  const { totalDogs, dogsPerPage } = this.props
  for (let i = 1; i <= Math.ceil(totalDogs / dogsPerPage); i++) {
    pageNumbers.push(i);
  }

  this.setState({ pageNumbers })
}
componentDidMount(){
const{pageNumbers=[]}=this.state
const{totalDogs,dogsPerPage}=this.props

对于(让i=1;i不要直接在react组件中变异
状态
。使用
设置状态
进行所有更新

componentDidMount() {
  const pageNumbers = [];
  for (
    let i = 1;
    i <= Math.ceil(this.props.totalDogs / this.props.dogsPerPage);
    i++
  ) {
    pageNumbers.push(i);
  }
  this.setState({ pageNumbers });
}

您不应该推送到状态数组;您需要创建数组,然后调用
this.setState
来更新状态。
componentDidMount
是正确的位置(除非在安装comp时道具发生变化,在这种情况下,您需要
componentdiddupdate
)你不需要第一个
…s
。谢谢,我没有意识到我在切换到comp类后没有更改状态操纵。顺便说一下,我使用了shouldComponentUpdate,这阻止了第二个重新渲染周期的发生。我尝试了这个,但列表没有显示。如果我使用componentWillMount()然后它工作了…对我来说工作很好,我创建了一次演示检查。忽略样式,我这样做了。但是列表仍然没有显示在UI中?不确定我看到了什么,我真的用你的代码交换了代码,但它不工作了…不确定为什么会发生这种情况。有什么想法吗?
componentDidMount() {
  const pageNumbers = [];
  for (
    let i = 1;
    i <= Math.ceil(this.props.totalDogs / this.props.dogsPerPage);
    i++
  ) {
    pageNumbers.push(i);
  }
  this.setState({ pageNumbers });
}
componentDidMount() {
  this.setState({
    pageNumbers: Array.from(
      { length: Math.ceil(this.props.totalDogs / this.props.dogsPerPage) },
      (_, i) => i + 1
    ),
  });
}