所以,如果想在路由组件的子组件中使用 history ,需要使用 withRouter 包裹:
import React, { PureComponent } from \'react\'; import { withRouter } from \'react-router-dom\'; class 子组件 extends PureComponent { goHome = () => { this.props.history.push(\'/home\') } render() { console.log(this.props) return ( <div onClick={this.goHome}>子组件</div> ) } } export default withRouter(子组件); 9. 路由过渡动画 import { TransitionGroup, CSSTransition } from "react-transition-group"; class App extends Component { render() { return ( <Provider store={store}> <Fragment> <BrowserRouter> <div> <Header /> {/* 最外部的<Route></Route>不进行任何路由匹配,仅仅是用来传递 location */} <Route render={({location}) => { console.log(location); return ( <TransitionGroup> <CSSTransition key={location.key} classNames=\'fade\' timeout={300} > <Switch> <Redirect exact from=\'/\' to=\'/home\' /> <Route path=\'/home\' exact component={Home}></Route> <Route path=\'/login\' exact component={Login}></Route> <Route path=\'/write\' exact component={Write}></Route> <Route path=\'/detail/:id\' exact component={Detail}></Route> <Route render={() => <div>Not Found</div>} /> </Switch> </CSSTransition> </TransitionGroup> ) }}> </Route> </div> </BrowserRouter> </Fragment> </Provider> ) } } .fade-enter { opacity: 0; z-index: 1; } .fade-enter.fade-enter-active { opacity: 1; transition: opacity 300ms ease-in; } 10. 打包部署的路由配置项目执行npm run build后,将打包后的build文件当大 Nginx 配置中。
如果 react-router 路由 使用了 history 模式(即<BrowserRouter>),那么在 Nginx 配置中必须加上:
location / { ··· ··· try_files $uri /index.html; ··· ··· } }如果 react-router 路由 使用了 hash 模式(即<HashRouter>),那么在 Nginx 中不需要上面的配置。