首页 > 解决方案 > 在 map 函数中调用 useState 钩子导致无限循环

问题描述

我目前正在构建一个动态表单引擎,并且我想在呈现答案摘要组件时显示来自 redux 存储的结果。我认为最好的方法是拥有“完整”状态并在加载 answerSummary 组件后将其设置为 true ,但是在 map 函数中执行此操作不起作用并引发无限循环反应错误。

代码在这里:

function App() {
  let [complete, setComplete] = useState(false);
  return (
    <div>
      <h1>Form App Prototype</h1>
      <Router>
        <Switch>
          {Object.values(Database.steps).map(step => {
            step.name === 'answerSummary' ? setComplete(true) : setComplete(false);
            return (

              <Route exact path={`/${step.name}`} render={() =>
                <Step step={step} />

              }
              />
            )
          })}
        </Switch>
      </Router>
        <br></br>
        <div style={{display: complete? 'block' : 'none'}}><StoreVisual/></div>

    </div>
  );
}

export default App;

编辑:我知道你无法在渲染中设置状态 - 我这样写是为了尝试传达我想要做的事情

标签: reactjsreact-hooks

解决方案


我对您的问题的理解是,您试图在安装答案摘要组件后显示结果。您可以通过使用useEffect在组件安装时运行的钩子来实现这一点。https://reactjs.org/docs/hooks-effect.html


推荐阅读