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
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()
.