>我正在尝试在请求数据方法中为如下所示的字符串变量设置状态
const ViewChangeRequest = () => {
const [requestStageValue, setRequestStage] = useState('');
const { data: requestData, loading: requestDataLoading, error: requestDataError } =
useQuery(GET_SPECIFICREQUEST, {
variables: { requestinputs: { id } },
});
if (requestData != null) {
setRequestStage(requestData.allRequests[0].requestStage.name); // getting error at here
requestData.allRequests.map((code) => {
requestDatasource.push({
id: code.id,
section: code.masterSection.name,
createdBy: code.createdBy,
type: code.requestType.name,
status: code.requestStage.name,
createat: code.createdAt,
});
return null;
});
}
};
export default withRouter(ViewChangeRequest);
取决于请求阶段值,我正在验证以下条件
if (requestStageValue === 'Request Submitted') {
stepNumber = 0;
} else if (requestStageValue === 'In Review') {
stepNumber = 1;
} else {
stepNumber = 2;
}
我在此行收到错误Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop
setRequestStage(requestData.allRequests[0].requestStage.name)
在设置字符串可浪性状态时,我无法理解我做错了哪里。
任何人都可以帮助我摆脱这种情况,这将非常感谢我,提前非常感谢。
好吧,你在函数中运行setRequestStage
。这将触发状态更新,这意味着函数再次运行(因为状态更新触发重新渲染(,这意味着setRequestStage
再次运行,这意味着状态再次更新,因此函数再次运行等等 - 无限循环。
如果要基于requestData
设置初始状态,请在useState
中声明时执行此操作:
const [requestStageValue, setRequestStage] = useState(
requestData !== null ? requestData.allRequests[0].requestStage.name : ''
);