我想在將axios請求提交給API並收集有效響應後重定向到我的家鄉路由。可以看出,我試圖使用上下文,但在這種情況下,我得到一個錯誤「上下文未定義」。在這種情況下,我如何導航到我的家鄉路線?我嘗試使用history.push,但似乎也沒有工作。任何想法將不勝感激?使用反應路由器導航
import React, {Component} from 'react'
import axios from 'axios'
import Home from './Home'
import {
BrowserRouter,
Link,
Route
} from 'react-router-dom'
class SignUp extends Component {
constructor(props){
super(props);
this.state = {
email: '',
password: ''
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
handleClick =() => {
axios
.post('http://localhost:9000/signup',{
email: this.state.email,
password: this.state.password
}).then(function(response){
console.log(response.data.success)
this.context.router.push('/home');
})
}
render(){
return(
<BrowserRouter>
<Route path="/" render={() => (
<div>
<h1> Sign Up</h1>
<input name="email" placeholder="enter your email" onChange={e => this.handleChange(e)}/>
<br/>
<input name="password" placeholder="enter your password" onChange={e => this.handleChange(e)}/>
<br/>
<button onClick={() => this.handleClick()}>submit</button>
<Route exact path="/home" component={Home}/>
</div>
)}/>
</BrowserRouter>
)
}
}
SignUp.contextTypes = {
router: React.PropTypes.func.isRequired
};
export default SignUp
該函數需要綁定,以便將相應的上下文傳遞給函數處理函數,例如())()' 或更簡單地說,'onClick = {this.handleClick.bind(this)}' – char
感謝您的輸入,我將它綁定到它,仍然上下文未定義! ! – hyper0009
你試過 從'react-router'導入{browserHistory}; browserHistory.push('/'); –