【发布时间】:2022-01-05 17:48:13
【问题描述】:
我有一个基本上是包含多个步骤的表单向导。该向导分为两部分:标签和内容。当内容组件更改其内部状态时,例如从 incomplete 到 error 或其他内容,我希望向导更新标签。我遇到的问题是从contents 组件中获取状态,尝试将其保存在wizard 组件中作为状态,以便我可以更新labels 导致无限循环。
虽然我理解这个问题,但我真的不知道如何解决它。这是一个非常最小的示例,我的真实组件使用一些高级功能,例如cloneElement 将道具传递给用户组件,而无需担心设置 10 个不同的道具。到目前为止,这一直完美无缺。
所以我明白每次我更新我的主要组件状态时,它都会重新渲染子组件,这将永远调用相同的设置状态函数。我能做些什么呢?
import React from "react";
import "./styles.css";
// This component containsLabel children
interface LabelState {
error: boolean;
}
interface LabelGroupProps {
states: LabelState[],
}
const LabelGroup = (props: LabelGroupProps) => {
return (<div>I am Comp A</div>)
}
// This component contains Component children
interface ContentState {
error: boolean;
}
interface ContentGroupProps {
getStates: (state: ContentState, index: number) => void
}
const ContentGroup = (props: ContentGroupProps) => {
// Indicate that step 2 has an error
props.getStates({
error: true
}, 2)
return (<div>I am Comp B</div>)
}
// This is the main wizard that contains both above components
// When the state of the a content component changes, the labels must be updated.
const App = () => {
const [states, setStates] = React.useState<LabelState[]>([]);
const getStates = (state: ContentState, index: number) => {
// This causes an infinite loop
// The intention is to save this state and then update the labels
const temp = [];
temp[index] = state;
setStates(prev => [...prev, ...temp])
}
return (
<div className="App">
<LabelGroup states={states}/>
<ContentGroup getStates={getStates}/>
</div>
);
};
export default App;
【问题讨论】:
标签: reactjs typescript