[英]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.