2017-09-15 252 views
0

我想在ReactJS項目(https://github.com/LeMueller/musicplayer-by-react/tree/dev)上使用路由器V4。但是我得到錯誤:AppUI未定義。通過這個演示(https://codepen.io/HeroBBQ/pen/jGEjNL)該方法運作良好。React路由器V4,未找到組件

我的代碼有什麼問題?

預先感謝您!

export default class Root extends Component{ 
constructor(props){ 
    super(props); 
    this.state={ 
     musiclist: MUSIC_LIST, 
     currentMusicItem: MUSIC_LIST[0] 
    } 

    this.PlayerUI=this.PlayerUI.bind(this); 
    this.ListUI=this.ListUI.bind(this); 
} 
PlayerUI =() => (
    <Player 
     cuerrentMusicItem={this.state.cuerrentMusicItem} 
    /> 
); 

ListUI =() => (
    <MusicList 
     cuerrentMusicItem={this.state.cuerrentMusicItem} 
     musicList={this.state.musicList} 
    /> 
); 

MainUI =() => (
    <Switch> 
     <Route exact path='/' component={PlayerUI}/> 
     <Route path='/list' component={ListUI}/> 
    </Switch> 
) 

AppUI =() => (
    <div> 
     <Header /> 
     <MainUI /> 
    </div> 
) 


render(){ 
    return(
     <HashRouter> 
      <AppUI /> 
     </HashRouter> 
    ) 
} 
} 

回答

0

如果你把AppUIclass,它將與this.AppUI引用。更好的移動功能組件出類:

const PlayerUI =() => (
     <Player 
      cuerrentMusicItem={this.state.cuerrentMusicItem} 
     /> 
    ); 

    const ListUI =() => (
     <MusicList 
      cuerrentMusicItem={this.state.cuerrentMusicItem} 
      musicList={this.state.musicList} 
     /> 
    ); 

    const MainUI =() => (
     <Switch> 
      <Route exact path='/' component={PlayerUI}/> 
      <Route path='/list' component={ListUI}/> 
     </Switch> 
    ) 

    const AppUI =() => (
     <div> 
      <Header /> 
      <MainUI /> 
     </div> 
    ) 

    export default class Root extends Component{ 
     constructor(props){ 
      super(props); 
      this.state={ 
       musiclist: MUSIC_LIST, 
       currentMusicItem: MUSIC_LIST[0] 
      } 

      this.PlayerUI=PlayerUI.bind(this); 
      this.ListUI=ListUI.bind(this); 
     } 

     render(){ 
      return(
       <HashRouter> 
        <AppUI /> 
       </HashRouter> 
      ) 
     } 
    } 

此外,它很可能是更好的綁定狀態屬性的道具傳遞給需要它們的組件。

+0

你好,謝謝你的回答。但是通過你的代碼,PlayerUI中的「this.state」不能指向根組件中的狀態。 –

+0

爲什麼不呢?它綁定在構造函數中? –

+0

this.PlayerUI = this.PlayerUI.bind(this);錯誤:PlayerUI未定義。 –