ReactJS渲染url改变的子视图

ReactJS rendering sub views with url change

本文关键字:视图 改变 渲染 url ReactJS      更新时间:2023-09-26

我试图将子视图(组件)呈现到基于组件上链接的导航菜单上,相应地改变url。我的路由器是:

const router = new Router(on => {
  on('*', async (state, next) => {
    const component = await next();
    return component && <App context={state.context}>{component}</App>;
  });
  on('/profile', async () => <ProfilePage />);
  on('/contact', async () => <ContactPage />);
  on('/login', async () => <LoginPage />);
  on('/register', async () => <RegisterPage />);
  on('*', async (state) => {
    const content = await http.get(`/api/content?path=${state.path}`);
    return content && <ContentPage {...content} />;
  });
  on('error', (state, error) => state.statusCode === 404 ?
    <App context={state.context} error={error}><NotFoundPage /></App> :
    <App context={state.context} error={error}><ErrorPage /></App>);
});
class ProfilePage extends React.Component {
  render() {
    var user = "Username";
    return (
      <div>
        <ProfileHead>
          <Cover user={user} />
          <Menu />
          <SubMenu />
        </ProfileHead>
        <ProfileBody>
          <ProfileHome />
        </ProfileBody>
      </div>
    );
  }
}
class Menu extends React.Component {
  render() {
    return (
      <div className="menu">
        <div className="menu-inner">
          <Nav followers="522234" following="133234" />
        </div>
      </div>
    );
  }
}
class Nav extends React.Component {
  render() {
    return (
      <div>
        <a href="#" className="menu-link active">Profile</a>
        <a href="#" className="menu-link">Portfolio</a>
        <a href="#" className="menu-link">Activity</a>
        <a href="#" className="menu-link">Following <span className="followCount">{this.props.following}</span></a>
        <a href="#" className="menu-link">Followers <span className="followCount">{this.props.followers}</span></a>
      </div>
    );
  }
}

我不确定这是如何实现的。任何帮助都会非常感激。我是React新手,学习缓慢。

我建议使用react-router

你可以创建嵌套的路由,每个路由加载其他子组件

var Router = require('react-router');
var Route = Router.Route;
// declare our routes and their hierarchy
var routes = (
  <Route handler={App}>
    <Route path="about" handler={About}/>
    <Route path="inbox" handler={Inbox}/>
  </Route>
);