Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何为不同的URL显示不同的组件?_Reactjs_Url - Fatal编程技术网

Reactjs 如何为不同的URL显示不同的组件?

Reactjs 如何为不同的URL显示不同的组件?,reactjs,url,Reactjs,Url,因此,如果页面URL只是一个/,我想呈现HomeNavbar组件。如果不是,那么我只需要BackNavbar。我试过了 {window.location.pathname === '/' ? <HomeNavbar /> : <BackNavbar />} 但这不起作用。为什么?请提供帮助。首先,您根本不必使用useffect(),因为您只需在jsx中调用navbar(),该jsx每次装载或渲染组件时都会运行 解决方案 // index.js file import {

因此,如果页面URL只是一个
/
,我想呈现
HomeNavbar
组件。如果不是,那么我只需要
BackNavbar
。我试过了

{window.location.pathname === '/' ? <HomeNavbar /> : <BackNavbar />}

但这不起作用。为什么?请提供帮助。

首先,您根本不必使用
useffect()
,因为您只需在jsx中调用
navbar()
,该jsx每次装载或渲染组件时都会运行

解决方案

// index.js file
import { BrowserRouter } from 'react-router-dom';

//... some codes
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
2使用历史挂钩

// App.js file
import { useHistory } from 'react-router-dom';

const App = () => {
  const history = useHistory();

  const navbar = () => {
    if (history.location.pathname === '/') {
        return <HomeNavbar />;
    } else {
        return <BackNavbar />;
    }
  };

  return (
    <div className='App'>
        {navbar()}
    </div>
  )
}

export default App;
或者,如果您的组件不是来自
,您可以使用
with router
高阶组件包装您的组件,现在您可以访问道具

我更喜欢使用路由器
,因为它比
useHistory
hook提供了更多的工作空间,因为它只提供了历史记录

如果使用方法1
console.log(道具)
或使用方法2
console.log(历史)
可以为您提供所有您可以尝试的东西

您必须签出此文件,或者可以通过
netninja


快乐编程:)

您是否使用类或函数来创建组件?提供更多信息。我的组件功能正常。@Jadeja先生,请查看更新的问题。我第一次尝试使用useHistory钩子,但似乎不起作用。但后来我尝试了路由器,它成功了!非常感谢@Mrjadeja,谢谢你的推荐。如果你在react方面需要帮助,请告诉我。查看联系人的个人资料:)您好@Mrjadeja我需要您的帮助:
// App.js file
import { withrouter } from 'react-router-dom';

const App = (props) => {
  const navbar = () => {
    if (props.history.location.pathname === '/') {
        return <HomeNavbar />;
    } else {
        return <BackNavbar />;
    }
  };

  return (
    <div className='App'>
        {navbar()}
    </div>
  )
}

export default withRouter(App);
// App.js file
import { useHistory } from 'react-router-dom';

const App = () => {
  const history = useHistory();

  const navbar = () => {
    if (history.location.pathname === '/') {
        return <HomeNavbar />;
    } else {
        return <BackNavbar />;
    }
  };

  return (
    <div className='App'>
        {navbar()}
    </div>
  )
}

export default App;
<BrowserRouter>
  <Switch>
    <Router exact path='/path/for/component' component={YourComponent} />
  </Switch>
</BrowserRouter>