我对React和Rails还是很陌生,但是我陷入了无法提交成功表单后无法使用React-Router移回到主应用程序“ /”的问题。我目前正在尝试使用withRouter和props.history.push方法。这是相关代码的片段。
App.js:
import React,{ Component } from 'react';
import { BrowserRouter as Router,Route } from 'react-router-dom';
import axios from 'axios';
import './App.css';
import Note from '../Note';
import NoteEdit from '../NoteEdit';
class App extends Component {
constructor(props) {
super(props)
this.state = {
note: ""
}
}
componentDidmount = () => {
this.getNote();
this.interval = setInterval(() => {
this.getNote();
},5000);
}
getNote = () => {
// Axios Get Request
}
handleChange = (event) => {
// Controlled Form Logic
this.setState({note: event.target.value})
}
handleSubmit = (event) => {
event.preventDefault();
axios.put('http://localhost:3001/notes/1',{
text: this.state.note
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
});
this.props.history.push("/");
}
render() {
return (
<Router>
<div classname="App">
<Route exact path="/" render={props =>
(<Note {...props} note={this.state.note}/>)
}/>
<Route path="/edit" render={props =>
(<NoteEdit {...props} note={this.state.note} handleSubmit={this.handleSubmit} handleChange={this.handleChange}/>)
}/>
</div>
</Router>
)
}
}
export default App;
完整的“ NoteEdit.js”子组件
import React,{ Component } from 'react';
import './NoteEdit.css';
import { withRouter } from 'react-router-dom';
class NoteEdit extends Component {
render() {
return (
<div classname="NoteEdit">
<form onSubmit={this.props.handleSubmit}>
<textarea classname="text_area" type="text" defaultvalue={this.props.note} onChange={this.props.handleChange}/>
<input type="submit" value="Save"/>
</form>
</div>
)}}
export default withRouter(NoteEdit);
当前错误是props在history.props中未定义。我应该把它绑在某个地方吗?在子组件中调用时,我尝试将其绑定到App.js和Submit方法中。
我对其进行了更新,以包含整个App.js文件,以便更好地了解发生了什么,并注释掉似乎不必要的内容。