2017-04-07 38 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 
} 
相关问题