【发布时间】:2019-10-14 11:23:19
【问题描述】:
您好,我是新来的反应,不幸的是我得到了这个代码的无限循环,我不知道为什么。这是有问题的代码:
if (projectInfo) {
console.log('Length is', projectInfo.length);
for (let i = 0; i < projectInfo.length; i++) {
setValues({ ...values, fromDates: projectInfo[i].fromDate });
console.log('i is', i);
}
}
整个组件在这里:
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import Map from '../../shared/components/Map/Map';
export default function FieldworkInofrmation(props) {
const projectInfo = props.props.fieldwork;
const [values, setValues] = React.useState({
fromDates: ' ',
});
if (projectInfo) {
console.log('Length is', projectInfo.length);
for (let i = 0; i < projectInfo.length; i++) {
setValues({ ...values, fromDates: projectInfo[i].fromDate });
console.log('i is', i);
}
}
return (
<Grid container spacing={3}>
<Grid item xs={12}>
<Box fontWeight="fontWeightBold" m={1}>
Fieldwork Information
</Box>
</Grid>
<Grid item xs={12}>
<Box fontWeight="fontWeightLight" m={1}>
Click on map point to view details for the point
</Box>
</Grid>
<Grid item xs={12}>
<Map />
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
Type:
</Box>
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
Period:
</Box>
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
From:
</Box>
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
To:
</Box>
</Grid>
<Grid item xs={6}>
<Box fontWeight="fontWeightLight" m={1}>
Coordinates:
</Box>
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
Station:
</Box>
</Grid>
<Grid item xs={1}>
<Box fontWeight="fontWeightLight" m={1}>
Location:
</Box>
</Grid>
</Grid>
);
}
我尝试在 for 循环的末尾插入“i++”,但仍然出现错误:“重新渲染过多。React 限制了渲染次数以防止无限循环”。我能做些什么来解决这个问题?
【问题讨论】:
-
我认为你可以使用
useEffect -
当你调用
setValues()时,React 将更新组件的状态。这意味着您的FieldworkInofrmation函数将再次完整运行。调用setValues()。等等等等,-> 无限循环。将状态更新放入一个函数中,然后将该函数传递给useEffect()。另外,看看你的代码,你为什么还要设置状态?您没有在其他任何地方使用它,并且它不会在您的组件内部发生变化。从外观上看,您只是将道具复制到状态? -
fromDates是values状态对象的属性。在(应该是什么)循环结束时,它将只有projectInfo属性中最后一个元素的值。基本上projectInfo[projectInfo.length - 1].fromDate。我猜这不是你想要的……values.fromDates假设是一个数组吗?或者可能是具有不同键的对象?如果您让我们知道您要实现的目标(以及fromDates的含义),那么回答问题会更容易
标签: javascript reactjs for-loop infinite-loop