[英]React conditional rendering with history
我有一个父组件,该组件为依次呈现的三个“表单”组件保持状态。 看起来像这样:
<Parent>
{ renderFormBasedOnState() }
</Parent>
FormA渲染,然后在单击下一步时,FormB渲染然后FormC渲染,均在父级中。
以前我是使用React Router来执行此操作的,但是问题是,我不希望用户将/ formb或/ formc设置为书签,因为那将是无效状态。
我可以使用switch语句来完成此操作,但是随后我失去了前进/后退按钮浏览器历史记录的功能-而且我基本上不想在组件中重新实现react-router。 最简单的方法是什么?
尚未在浏览器的背面尝试过,但看起来可能像这样:
export default class tmp extends React.Component {
state = {
currentVisibleForm: 'A'
}
onBackButtonEvent = (e) => {
if(this.state.currentVisibleForm !== 'A') {
e.preventDefault();
//Go back to the previous visible form by changing the state
} else {
// Nothing to do
}
}
componentDidMount = () => {
window.onpopstate = this.onBackButtonEvent;
}
render() {
return (
<Parent>
{this.state.currentVisibleForm === 'A' &&
<FormA />
}
{this.state.currentVisibleForm === 'B' &&
<FormB />
}
{this.state.currentVisibleForm === 'C' &&
<FormC />
}
</Parent>
)
}
}
告诉我是否有帮助!
因此,我能够使用history api进行此操作 ,但是微调可能不值得进行调整-我可能会回复。 在两个地方管理国家有点愚蠢。 请注意,此历史记录对象与应用程序的“路由器”组件相同,并且没有冲突。
state = {
FormData: {},
action: 'Form_1'
}
componentWillMount() {
this.unlistenHistory = history.listen((location) => {
if (location.state) {
this.setState(() => ({
action: location.state.action
}));
}
});
history.push(undefined, {action: 'FORM_1'});
}
componentWillUnmount() {
this.unlistenHistory();
}
finishForm1 = () => {
const action = 'Form_2';
history.push(undefined, { action });
this.setState((prevState) => ({
// business stuff,
action
}));
};
renderCurrentState() {
switch(this.state.action) {
case 'FORM_1':
return <Form1 />
...
}
}
render() {
return (
<div>
{ this.renderCurrentState() }
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.