React Router V4,找不到组件

时间:2017-09-15 12:28:07

标签: reactjs components router

我想在ReactJS项目(https://github.com/LeMueller/musicplayer-by-react/tree/dev)上使用Router V4。但我得到错误:未定义AppUI。通过这个演示(https://codepen.io/HeroBBQ/pen/jGEjNL),这种方法效果很好。

我的代码出了什么问题?

提前谢谢!

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>
    )
}
}

1 个答案:

答案 0 :(得分:0)

如果您将AppUI放在class中,则会引用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>
            )
        }
    }

此外,将绑定状态属性作为props传递给需要它们的组件可能更好。

相关问题