无状态组件React路由器

时间:2018-06-17 10:06:46

标签: reactjs redux react-router react-router-v4 react-component

我是React和Redux的新手,我实际上正在创建一个自己的代码,但我在无状态组件中遇到了路由器类的问题。

所以,实际上我需要使用this.props.history.push('/ somepath')路由到组件。这不会发生在无状态组件中。

My Stateless组件

import React from "react"; // eslint-disable-line no-unused-vars
import "bootstrap/dist/css/bootstrap.min.css";
import "./header.css";

const Header = () => ({

    handleAuthor() {
        this.props.history('/somepath')// this is not working
    },

    render(){
        return (
            <div className = "header">
                <h1 onClick = {this.handleAuthor.bind(this)}>{this.props.headerText}</h1>
            </div>
        );
    } 
});

export default Header;

我在另一个无状态组件中调用它,例如mainlayout

import React from "react"; // eslint-disable-line no-unused-vars
import Header from "../header/Header"; // eslint-disable-line no-unused-vars
import Footer from "../footer/Footer"; // eslint-disable-line no-unused-vars
import "./mainLayout.css";

const MainLayout = props => ({
    render() {
        return (
            <div className="App">
                <Header headerText = "RK Boilerplate"/>
                <div className = "mainLayout">
                    <main>{props.children}</main>
                </div>
                <Footer />
            </div>
        );
    }
});

export default MainLayout;

我的主文件index.js看起来像这样

import React from "react"; // eslint-disable-line no-unused-vars
import ReactDOM from "react-dom"; // eslint-disable-line no-unused-vars
import { matchRoutes, renderRoutes } from "react-router-config"; // eslint-disable-line no-unused-vars
import { Router } from "react-router-dom"; // eslint-disable-line no-unused-vars
import { Switch } from "react-router"; // eslint-disable-line no-unused-vars
import { Provider } from "react-redux"; // eslint-disable-line no-unused-vars
import store from "./store"; // eslint-disable-line no-unused-vars
import routes from "./routes"; // eslint-disable-line no-unused-vars
import MainLayout from "./components/mainLayout/MainLayout"; // eslint-disable-line no-unused-vars

import createHistory from "history/createBrowserHistory";
let history = createHistory();
const App =  document.getElementById("app");

export default App;

ReactDOM.render(
    <Provider store={store}>
        <MainLayout>
            <Router history= {history}>
                <Switch>
                    {renderRoutes(routes)}
                </Switch>
            </Router>
        </MainLayout>                 
    </Provider>, 
    App);

所以我需要的是我必须从标题路由到另一个组件,其中该组件和路径在路由器文件中给出

router.js

import Home from "../containers/Home";
import About from "../containers/About";
import CreateUser from "../containers/CreateUser";

import Layout from "../containers/Layout";

const routes = [
    { path: "/",
        exact: true,
        component: Layout
    },
    { path: "/home",
        exact: true,
        component: Home
    },
    {
        path:"/About",
        exact: true,
        component: About
    },
    {
        path:"/createUser",
        exact: true,
        component: CreateUser
    }
];

export default routes;

当我尝试从标题路由时,我收到了像undefined一样的错误。 我错过了什么,我应该在这里做任何改变。

提前致谢。

4 个答案:

答案 0 :(得分:5)

2019年,React Router v4现在为无状态/功能组件添加了useHistory钩子:

https://reacttraining.com/react-router/web/api/Hooks/usehistory

从文档中

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

答案 1 :(得分:1)

希望这不会太晚。我可以成功地从有状态组件进行重定向,但是我想将我的组件转换为无状态组件,因为使它成为有状态的唯一原因就是重定向位。我是新来的反应者,那里的大多数资源都不是很清楚。这就是我要做的。

import React from "react"; // eslint-disable-line no-unused-vars
import "bootstrap/dist/css/bootstrap.min.css";
import "./header.css";

const Header = (props) => {
    return (
        <div className = "header">
            <h1 onClick = {props.history.push('/some-path')}>{props.headerText}</h1>
        </div>
    );
} 

export default Header;

答案 2 :(得分:0)

您可以直接导入历史记录对象并从中推送。例如,尝试以下代码。

import React from "react"; // eslint-disable-line no-unused-vars
import "bootstrap/dist/css/bootstrap.min.css";
import "./header.css";
import history from "/your/history/path" //try this

const Header = () => ({

    handleAuthor() {
        history.push('/somepath')// change to this
    },

    render(){
        return (
            <div className = "header">
                <h1 onClick = {this.handleAuthor.bind(this)}>{this.props.headerText}</h1>
            </div>
        );
    } 
});

export default Header;

创建如下所示的浏览器历史记录,并通过导入在每个位置使用它。

import createBrowserHistory from 'history/createBrowserHistory';

export default createBrowserHistory({});

答案 3 :(得分:0)

通过使用withRouter对我有用(加上忽略打字稿警告):

import { withRouter } from 'react-router-dom';

...

type Props = { myProp: boolean };

// @ts-ignore
export const MyComponent: FC<Props> = withRouter(({ myProp, history }) => {

...

})