私のAxiosリクエストをAPIに送信して有効な応答を収集すると、自分のホームルートにリダイレクトしたいと思う。見ての通り、Imはコンテキストを使用しようとしていますが、この場合は「コンテキストが定義されていません」というエラーが表示されます。この場合、私は自分のホームルートにどのように移動できますか?私は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
適切なコンテキストが関数ハンドラに伝達されるように、関数をバインドする必要があります。 'on.handleClick.bind(this)}' 以上を入力すると、 'onClick = {this.handleClick.bind(this)}' – char
入力していただきありがとうございます。これをバインドしましたが、まだコンテキストは定義されていません! !! – hyper0009
あなたは試しました 'react-router'から{browserHistory}をインポートしてください。 browserHistory.push( '/'); –