簡體   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