2017-04-07 76 views
0

新的reactJS和我試圖讓我的組件之一交替通過許多CRUD狀態(創建對象,列出對象,更新對象,刪除對象),每個組件將顯示適當的形式。 ..reactJS如何在很多應用程序狀態之間切換

我想這樣做,但我不明白我的想法是否有缺陷。

constructor() { 
    super(props); 

    this.state = { 
     list: true, 
     edit: false, 
     create: false, 
     // and so on for CRUD operations 
} 

再後來會有一個方法......

handleCRUDViewChange(newView) { 
    // flip everything to false... 
    // turn the correct one to true 
} 

然後在渲染會是這樣的......

switch (true) { 
case this.state.list: 
    <ListComponent /> 
case this.state.edit: 
    <EditComponent /> 
// and so on... 
} 

是我的思想的聲音?這是做事的「反應」方式嗎?

回答

1

是的,你是在正確的軌道上。您可能要簡化這個有點 - ,你不必送CRUD模式特定狀態的部件,而在實際情況下,你可能要多寫一些邏輯來

const MODES = {LIST: 0, EDIT: 1, CREATE: 2}, 
CRUD_COMPONENTS = [ListComponent, EditComponent, CreateComponent]; 
constructor(){ 
    this.state = {"mode" : MODES.LIST}; 
}, 
handleCRUDViewChange(newView) { 
    // decide the relevantMode value out of LIST, EDIT or CREATE based on your logic 
    // and then update state 
    this.setState({"mode": MODES[relevantMode]}); 
} 
render(){ 
    let Component = CRUD_COMPONENTS[this.state.mode]; 
    return <Component />; 
} 

在您簡單的例子存儲特定於模式的道具並將它們傳遞給選定的模式組件。

1

對於每個粗暴視圖,沒有必要維護一個單獨的狀態變量。該代碼可以被簡化爲

constructor() { 
super(props); 
this.state = { 
     crudView : 'list' 
    } 
} 

handleCRUDViewChange(newView) { 
this.setState({ 
    crudView : newView 
    })  
} 

的條件呈現也必須相應地改變

switch(this.state.crudView) { 
case 'list': 
    <ListComponent/> 
case 'edit': 
    <EditComponent/> 
//and so on 
} 
相關問題