How to push to History in React Router v4?

后端 未结 21 1862
不思量自难忘°
不思量自难忘° 2020-11-22 00:27

In the current version of React Router (v3) I can accept a server response and use browserHistory.push to go to the appropriate response page. However, this isn

21条回答
  •  不思量自难忘°
    2020-11-22 01:15

    I was able to accomplish this by using bind(). I wanted to click a button in index.jsx, post some data to the server, evaluate the response, and redirect to success.jsx. Here's how I worked that out...

    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 (
                
    ) } } 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 (
            
    Hey cool, got it.
    ) } export default Success

    So by binding this to postData in index.jsx, I was able to access this.props.history in request.js... then I can reuse this function in different components, just have to make sure I remember to include this.postData = postData.bind(this) in the constructor().

提交回复
热议问题