繁体   English   中英

我有一个错误:重新渲染太多。 React 限制渲染次数以防止无限循环

[英]I have an error: Too many re-renders. React limits the number of renders to prevent an infinite loop

我是网站上的新人,这是我的第一条评论。 我有一个我无法解决的问题。 我是 React 的新手,我构建了一个组件,它从 redux 获取一个名为 Categories 的数组。

我想将此数组作为列表打印给用户。

这就是我想要做的,但我收到了错误。

错误:重新渲染太多。 React 限制渲染次数以防止无限循环。


import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import withStyles from '@material-ui/core/styles/withStyles';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';

//Redux
import { connect } from 'react-redux';
import { getCategories } from '../../redux/actions/dataActions';

function valuetext(value) {
  return `${value}`;
}

const styles = (theme) => ({
  ...theme.spreadThis
});

function PreferenceList(props) {
  const {
    classes,
    user: loading
    }
  } = props;
  const [filledCategories, setFilledCategories] = React.useState(props.categories);

  if (loading) {
    console.log ("nothing for now...");
  }

  const handleChange = (event, value) => {
    console.log("nothing for now...")
  };

  return (
    <React.Fragment>
      <List dense className={classes.root}>
        {props.data.categories.map((value, index) => {
          console.log(value);
          const labelId = `checkbox-list-secondary-label-${index}`;
          return (
            <ListItem key={value[Object.keys(value)[0]]} button>
              <ListItemText id={labelId} primary={`${Object.keys(value)[0]} with rating ${value.rating}`} />
              <ListItemSecondaryAction>
                <TextField
                  id={`input-${index}`}
                  name={`input-${index}`}
                  type={`input-${index}`}
                  label={`input-${index}`}
                  value={filledCategories[index]}
                  onChange={handleChange(index)}
                  inputProps={{ 'aria-labelledby': labelId }}
                  fullWidth
                />
              </ListItemSecondaryAction>
            </ListItem>
          );
        })}
      </List>
    </React.Fragment>
  );
}

const mapStateToProps = (state) => ({
  user: state.user,
  data: state.data
});

export default connect(
  mapStateToProps, { getCategories }
)(withStyles(styles)(PreferenceList));

我不太明白错误在哪里,我对这整件事都很陌生。 我的假设是我可能出于某种原因对页面进行了过多的刷新。 但我不知道如何防止它。 这对我来说很难

将 TextField 组件内的onChange更改为箭头 function。 在您的情况下handleChange被称为无限次。

onChange={() => handleChange(index)}

我通过向组件添加密钥解决了这个问题。 我遇到了同样的错误,但我遇到了一个稍微不同的问题。 当我 select 打开新显示的列表中的一个元素时,有一个文本区域。 由于它们在渲染树中是相同的,因此会引发错误。 所以添加一个密钥解决了这个问题。 希望这对某人有帮助。

暂无
暂无

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

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