2016-05-19 5 views
2

私はProfileコンポーネントを持っており、ユーザーのアクション(aタグをクリック)によって異なるコンポーネントをレンダリングする必要があります。私は情報が渡され、正しいコンポーネントの状態が更新されています。ただし、Profileコンポーネントが再レンダリングされた場合でも、新しく選択されたコンポーネントではなく、同じコンポーネントがレンダリングされます。リア・レンダリングをしても正しいコンポーネントが表示されない

class Profile extends Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     currentComponent: 'sales' 
    } 

    this.changeComponent = this.changeComponent.bind(this); 
    } 

    changeComponent(component){ 
    console.log('You are trying to change component!'); 
    console.log(this); 
    this.setState({currentComponent: component}); 
    } 

    render(){ 
     let component; 
     switch(this.state.currentComponent){ 
     case 'sales': 
      component = <Sales />; 
      break; 
     case 'income': 
      component = <Income />; 
     default: 
      component = <Sales />; 
     } 
     const menuItems = [ 
     { 
      text: 'Sales' 
     }, 
     { 
      text: 'Team' 
     }, 
     { 
      text: 'Income' 
     }, 
     { 
      text: 'Edit' 
     } 
     ] 
     console.log(this.state); 
     return <div id="profileWrap"> 
     <div id="profileMenu"> 
      <NavMenu menuItems={menuItems} currentComponent={this.state.currentComponent} changeComponent={this.changeComponent}/> 
     </div> 
     {component} 
     </div> 
    } 
} 

そして、私のSales/IncomeコンポーネントSalesの代わりにIncomeとちょうど

import React, {Component} from 'react'; 
import {Link} from 'react-router'; 

class Sales extends Component { 
    render(){ 
     return(<h1>This is Sales!</h1>) 
    } 
} 

export default Sales; 

です。

ご覧のとおり、Profileコンポーネントの内部では、その機能にアクセスしたときに私は覚えています。thisはその時点で(どちらも正しいように見えます)、状態も記録しています再レンダリング時には、正しい状態が使用されていることを示しています。それは私のswitch文で何か?

if/elseif文、そのすべての作品に自分のswitch文を変更した後、編集

switchが更新されないのはなぜですか?

答えて

4

あなたのswitch文でbreakを逃している:

switch(this.state.currentComponent){ 
    case 'sales': 
     component = <Sales />; 
     break; 
    case 'income': 
     component = <Income />; 
     break; // <-- need this here or will fall through to default. 
    default: 
     component = <Sales />; 
    } 

アップデートを:あなたはまた、あなたのmenuItems配列に要素を追加することによって、この全体のことを回避することができます。

this.state = { currentComponent: <Sales /> } 

... 

const menuItems = [ 
    { 
     text: 'Sales' 
     component: <Sales /> 
    }, 
    ... 
    ] 

その後でレンダリング:{ this.state.currentComponent }

+0

聖なるモーセを...それは愚かな間違いでした。私はそれをキャッチするのに役立ちますありがとう5分後、私はこれを答えとして受け入れます! –

+1

np :)私の答えを更新しました。おそらくそのswitch文は必要ありません。 – azium

+0

それは実際には賢くスマートですし、私はそれをやってどうやって行くのだろうと思っていました –

関連する問題