react-router-dom 链接在 app.js(父组件)中有效,但在子组件中无效

Posted

技术标签:

【中文标题】react-router-dom 链接在 app.js(父组件)中有效,但在子组件中无效【英文标题】:react-router-dom link works in app.js(parent component) but doesn't work in child component 【发布时间】:2019-02-09 00:09:18 【问题描述】:

我在“app.js”(父组件)和“home.js”中有“导航”组件,通过设置header height: 90vh ,有条件地仅在主页中的标题底部有响应式空格。

为了做到这一点,我在“Home.js”的标题标签中包含了

问题来了, 导航链接在 app.js 中运行良好,但在 home.js 中甚至无法点击。

Homepage Header Image

index.js

import React from 'react';
import  render  from 'react-dom';
import  Provider  from 'react-redux';
import  ConnectedRouter as Router  from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import Store from './Store';
import Routes from './Routes';

require('./styles/main.scss');

const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store=Store>
    <Router history=createHistory()>
      <Routes />
    </Router>
  </Provider>,
  root,
);

Routes.js

import React from 'react';
import  Switch, Route  from 'react-router-dom';
import  hot  from 'react-hot-loader';
import App from './src/app';
/* --- Components --- */
import Loader from './src/shared/loader';

const Home = Loader(
      loader: () => import('./src/components/Home' /* webpackChunkName: 'Home' */),
    );

const Login = Loader(
      loader: () => import('./src/components/login' /* webpackChunkName: 'Login' */),
    );

const NoMatch = Loader(
      loader: () => import('./src/shared/NoMatch' /* webpackChunkName: 'NoMatch' */),
    );

const routes = () => (
      <div>
        <App />
        <Switch>
          <Route exact path="/" component=Home />
          <Route path="/login" component=Login />
          <Route component=NoMatch />
        </Switch>
      </div>
    );

const Routes =
      !module.hot || process.env.NODE_ENV === 'production'
        ? routes
        : hot(module)(routes);

export default Routes;

App.js

import React from 'react';
import  Helmet  from 'react-helmet';
/* --- shared --- */
import Loader from './shared/loader';

const Nav = Loader(
  loader: () => import('./shared/nav' /* webpackChunkName: 'Nav' */),
);

const App = props => 
  const isHomepage = window.location.pathname === '/';

  return (
    <div id="app">
      <Helmet>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>###</title>
        <meta property="og:title" content="###" />
        <meta property="og:description" content="###" />
        <meta property="og:type" content="###" />
        <meta property="og:url" content="###" />
        <meta property="og:image" content="###" />
        <link type="text/plain" rel="author" href="http://domain/humans.txt" />
        <link type="text/plain" rel="author" href="http://domain/robots.txt" />
        <link
          href="https://fonts.googleapis.com/css?family=Nanum+Gothic"
          rel="stylesheet"
        />
        <link
          rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"
        />
      </Helmet>
      props.children
      !isHomepage ? <Nav /> : null
    </div>
  );
;

export default App;

nav.js

import React from 'react';
/* --- shared --- */
import * as data from './data';
import Ul from './ul';

const Nav = () => (
  <div className="nav">
    <div className="flex justify-between nav--top">
      <p className="mh-auto f-mini fw3">
        상담전화
        <span className="f-regular"> xxx&#45;xxxx&#45;xxxx</span>
      </p>
      <Ul links=data.redirectToLogin />
    </div>
    <h1>
      <Ul links=data.redirectToHome />
    </h1>
    <div className="hr-center">
      <Ul links=data.nav />
    </div>
  </div>
);

export default Nav;

ul.js

import React from 'react';
import  Link  from 'react-router-dom';

const Ul = ( links ) => (
  <ul className="nav-menu">
    links &&
      links.map(e => (
        <li>
          <Link className=e.className key=e.id to=e.to>
            e.name
          </Link>
        </li>
      ))
  </ul>
);

export default Ul;

Home.js

import React from 'react';
/* --- Components --- */
import HomeMain from './Home.main';
/* --- Shared --- */
import Nav from '../shared/nav';

const Home = () => (
  <div>
    <header>
      <Nav />
      <div className="header-text--box">
        <h2>
          <span className="f-regular f-en lh-3">NO MSG!</span>
          <br />
          오늘도 열심히 일하는 당신에게 착한 가격의 집밥을 선물하세요.
        </h2>
      </div>
    </header>
    <HomeMain />
  </div>
);

export default Home;

版本

react: 16.4.2 
react-dom: 16.4.2 
react-redux: 5.0.7 
react-router-dom: 4.3.1 
react-router-redux: 5.0.0-alpha.9

感谢您抽出宝贵时间帮助我。

【问题讨论】:

【参考方案1】:

我将在此处制作一个我通常使用的设置的简化示例。那么,这种方法呢?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import Provider from "react-redux/es/components/Provider";
import  createStore, applyMiddleware  from 'redux';
import rootReducer from '../reducers/rootReducer';
import thunk from 'redux-thunk';

// Usually I would do this in an external file, but here I'm configuring my store

const myStore = configureStore(initialState) 
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk)
  );
    

// After that, I'm wrapping my App component inside of the Provider and passing in the configured store

ReactDOM.render((
    <Provider store=myStore >
        <App/>
    </Provider>
), document.getElementById('root'));

App.js

import React,  Component  from 'react';
import  BrowserRouter  from 'react-router-dom'
import PrimaryLayoutContainerComponent from "../containers/PrimaryLayoutContainer";

// In my App.js I'm wrapping my primary layout container with BrowserRouter to get access to the history and also passing in the props

class App extends Component 
    render() 
        return (
            <BrowserRouter>
                <PrimaryLayoutContainerComponent ...this.props/>
            </BrowserRouter>
        );
    

export default App;

PrimaryLayoutContainerComponent.js 在这个(主容器)中,我将充分利用我以前的配置以及关于 Redux 状态管理提供和需要的任何内容。在这个阶段我还使用 withRouter 来访问历史对象的属性。

import React from 'react';
import  connect  from 'react-redux';
import  bindActionCreators  from 'redux';
import * as myActions from '../actions';
import PrimaryLayout from "../components/layout/PrimaryLayout";
import  withRouter  from 'react-router';
import PropTypes from 'prop-types';


class PrimaryLayoutContainerComponent extends Component 
    render() 
        return (
            <div>
                 //Here we pass our history as props
                <PrimaryLayout  history=this.props.history 
                                propsX=this.props.propsX

                                propsY=this.props.actions.propsY
                />
            </div>
        )
    


// In these (and all other cases) I would highly recommend using propTypes.
// They could give you the answer in where the issues might be in your future development 

PrimaryLayoutContainerComponent.propTypes = 
    loggedUser: PropTypes.string,
    actions: PropTypes.object.isRequired
;

const mapStateToProps = (state) => 
    return  xxxx 


const mapDispatchToProps = (dispatch) => 
    return 
        actions: bindActionCreators(myActions, dispatch)
    ;


export default withRouter(connect(mapStateToProps, mapDispatchToProps)(PrimaryLayoutContainerComponent));

...最后在我的 Primary Layout Component 我会这样定义我的所有路线:

PrimaryLayoutComponent.js

import React,  Component  from 'react';
import  Switch, Route, Redirect, Link  from 'react-router-dom';
// ... import all my compoenents


class PrimaryLayout extends Component 
    constructor(props) 
        super(props);
        this.state = 
            currentRoute: '' // I would use the state to dynamically change the  
                             // routes depending on which one was clicked
        
    



    componentWillReceiveProps(nextProps) 
        this.setState(
            currentRoute: nextProps.history.location.pathname
        )
    

    componentWillMount() 
        this.setState(
            currentRoute: this.props.history.location.pathname
        )
    

    render() 

        const  currentRoute  = this.state;

        return (
            <div className="wrapper">
                <header className="xxxx" role="banner">
                    <div className="container">
                        <div className="xxxxx">


                           <Link to="/home">
                             <img src=logo /> Your App Name
                           </Link>
                            <ul className="navbar__menu">
                                    <li className=currentRoute === "/home" ? "active" : "">
                                        <Link to="/home"> Home </Link>
                                    </li>

                                    <li className=currentRoute === "/componentOne" ? "active" : "">
                                        <Link to="/componentOne"> componentOne</Link>
                                    </li>

                                    <li className=currentRoute === "/componentTwo" ? "active" : "">
                                        <Link to="/componentTwo"> componentTwo</Link>
                                    </li>
                            </ul>

                        </div>
                    </div>
              </header>

// At the very end, I'm using the Switch HOC and defining my routes inside of a main tag

               <main>
                <Switch>
                      <Route path='/home' component=HomeContainerComponent />
                  <Route path='/componentOne' component=componentOne />               
                  <Route path='/componentTwo' component=componentTwo />
                  <Redirect to="/home"/>
                </Switch>
                </main>
            </div>
        )
    


export default PrimaryLayout;

希望我的方法对您有所帮助,如果您有任何其他问题,请告诉我。我会尽快回复他们的

【讨论】:

嗨@Bigga_HD,感谢您的回答。从您的代码中学习,我的代码现在将历史作为道具传递,我也在考虑使用状态来跟踪路线。我想知道您为什么在 PrimaryLayoutComponent.js 中使用 componentWillReceivepRrops() 方法。 ComponentWillMount() 方法根据 props 变化更新状态。 @Jiah827 - componentWillMount 在第一次渲染时被调用一次。后续渲染调用 componentWillReceiveProps。问题是我不确定 prop 是否会在调用第一个渲染时被初始化。 (道具取决于异步数据)。所以 - 我不能把代码放在 componentWillMount 中。但是,如果我将它放在 componentWillReceiveProps 中,然后在组件链中更改更高的内容,以便同步完成数据,那么我在 componentWillReceiveProps 中的代码永远不会运行。 这就是我通常用来处理异步数据和 HOC 的方式。如果componentWillMount 适合您的情况,那太好了,只使用那个:) 如果我的代码有任何帮助,请考虑至少投赞成票。谢谢。但我不会担心,componentWillReceiveProps 已被弃用,将在下一个主要版本中删除。 - > React 17 ...有关更多信息,我建议阅读这篇文章。 reactjs.org/blog/2018/03/27/update-on-async-rendering.html 我明白了。谢谢Bigga_HD!我已经对你的答案表示赞同,但显然它不会改变公开显示的帖子分数,因为我还没有足够的声誉:/ 别担心。我有点开玩笑。我很高兴它有帮助;)【参考方案2】:

看你的造型,好像是headerhas a negative z-index

通过设置负z-index,这可能会干扰&lt;header&gt;(即您的&lt;nav&gt; 组件)的子组件接收点击事件和/或正确响应光标。

我建议从您的 header.scss 中删除 z-index: -1; 以解决您的问题。希望对您有所帮助!

【讨论】:

很高兴我能帮上忙 :-)

以上是关于react-router-dom 链接在 app.js(父组件)中有效,但在子组件中无效的主要内容,如果未能解决你的问题,请参考以下文章

React-router-dom:TypeError:无法读取未定义的属性(读取“位置”)

./src/App.js 尝试导入错误:“Switch”未从“react-router-dom”导出

如何在 react-router-dom 链接中传递参数? [复制]

如何在 React.js 中使用 react-router-dom 保持 App() 级别状态不重置?

错误:./src/App.js 尝试导入错误:“Switch”未从“react-router-dom”导出

我的 React App 从不加载 localhost:3000 它只是一直在旋转(认为 React-Router-Dom 是问题)