如何在React Router v4中推送到历史记录?

reactjs React.js

阿飞Pro

2020-03-10

在当前版本的React Router(v3)中,我可以接受服务器响应并用于browserHistory.push转到相应的响应页面。但是,这在v4中不可用,我不确定哪种适当的处理方式。

在此示例中,使用Redux,当用户提交表单时components / app-product-form.js调用this.props.addProduct(props)服务器返回成功后,该用户将被带到“购物车”页面。

// actions/index.js
export function addProduct(props) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
      .then(response => {
        dispatch({ type: types.AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/cart'); // no longer in React Router V4
      });
}

如何从React Router v4的功能重定向到购物车页面?

第401篇《如何在React Router v4中推送到历史记录?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
斯丁Sam斯丁 2020.03.10

现在,React路由器V4允许使用以下历史记录道具:

this.props.history.push("/dummy",value)

然后,只要位置prop可用(state:{value}不是组件状态),就可以访问该值

MandyNear乐 2020.03.10

我能够通过使用来完成此操作bind()我想要单击一个按钮index.jsx,将一些数据发布到服务器,评估响应,然后重定向到success.jsx这就是我的解决方法...

index.jsx

import React, { Component } from "react"
import { postData } from "../../scripts/request"

class Main extends Component {
    constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.postData = postData.bind(this)
    }

    handleClick() {
        const data = {
            "first_name": "Test",
            "last_name": "Guy",
            "email": "test@test.com"
        }

        this.postData("person", data)
    }

    render() {
        return (
            <div className="Main">
                <button onClick={this.handleClick}>Test Post</button>
            </div>
        )
    }
}

export default Main

request.js

import { post } from "./fetch"

export const postData = function(url, data) {
    // post is a fetch() in another script...
    post(url, data)
        .then((result) => {
            if (result.status === "ok") {
                this.props.history.push("/success")
            }
        })
}

success.jsx

import React from "react"

const Success = () => {
    return (
        <div className="Success">
            Hey cool, got it.
        </div>
    )
}

export default Success

因此,通过绑定thispostDatain index.jsx,我可以访问this.props.historyin request.js...然后可以在不同的组件中重用此函数,只需确保记得记得包含this.postData = postData.bind(this)在中constructor()

Harry前端神无 2020.03.10

this.context.history.push 不管用。

我设法使推像这样工作:

static contextTypes = {
    router: PropTypes.object
}

handleSubmit(e) {
    e.preventDefault();

    if (this.props.auth.success) {
        this.context.router.history.push("/some/Path")
    }

}
Gil西里斯丁 2020.03.10

根据React Router v4文档-Redux深度集成会话

需要深度集成以:

“能够通过调度动作进行导航”

但是,他们建议此方法作为“深度集成”的替代方法:

“与其调度动作来导航,不如传递所提供的历史对象以将组件路由到您的动作并在那里进行导航。”

因此,您可以使用withRouter高阶组件包装组件:

export default withRouter(connect(null, { actionCreatorName })(ReactComponent));

它将历史API传递给道具。因此,您可以调用动作创建者,将历史作为参数进行传递。例如,在您的ReactComponent内部:

onClick={() => {
  this.props.actionCreatorName(
    this.props.history,
    otherParams
  );
}}

然后,在您的actions / index.js内部:

export function actionCreatorName(history, param) {
  return dispatch => {
    dispatch({
      type: SOME_ACTION,
      payload: param.data
    });
    history.push("/path");
  };
}
路易EvaSam 2020.03.10

现在,通过react-router v5,您可以使用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>
  );
}

有关更多信息,访问:https : //reacttraining.com/react-router/web/api/Hooks/usehistory

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android