reactjs - 在 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;
编辑:我知道你无法在渲染中设置状态 - 我这样写是为了尝试传达我想要做的事情
解决方案
我对您的问题的理解是,您试图在安装答案摘要组件后显示结果。您可以通过使用useEffect
在组件安装时运行的钩子来实现这一点。https://reactjs.org/docs/hooks-effect.html
推荐阅读
- json - 从列表中的 React Native 上的 XML 返回和呈现循环文本项
- android - scrollView 中的 fillViewPort 到底是做什么的?
- java - 如何修复 HiveMQ 客户端中未定义的 MqttChannelInitializer 构造函数?
- mysql - 在两个不同的列中分离压缩数据
- sql-server - spring boot中不同数据库的多个数据库模式
- sql - 索引:当 Status = 'S' 时避免表中的重复
- bash - 如何扩展 YAML 锚点和别名并在 Bash 中获取生成的 YAML?
- r - 如何从应用函数中的 lm 函数中提取 p 值?
- c++ - 如何在 C++ 中将 struct 成员的十六进制值写入 unsigned char 数组?
- c# - Unity 不会创建项目,只会创建一个阻止 IntelliSense 工作的 cs 文件