![](/img/trans.png)
[英]Ember is not updating my page unless I go to home and the back to the route
[英]How do I route my application back to the home page from a form using React?
我对 React 和 Rails 还很陌生,在成功提交表单后,我不知道如何使用 React-Router 回到我的主应用程序“/”。 我目前正在尝试使用 withRouter 和 props.history.push 方法。 以下是相关代码的片段。
应用程序.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);
当前的错误是在 history.props 中未定义 props。 我应该在某个地方绑定它吗? 在我的子组件中调用时,我尝试在我的 App.js 和 Submit 方法中绑定它。
我更新了它以包含整个 App.js 文件,以便更好地了解发生了什么,并注释掉似乎不必要的内容。
我不知道 App.js 的导出方法,但是如果组件不是使用withRouter
导出的,那么历史道具可能不可用。
一个简单的解决方案可能是只使用window.location = '/';
而不是history.push()
。
感谢@seanulus 提供解决此问题的正确方法。
我的 handleSubmit function 只需要存在于 NoteEdit.js 组件中,并使用道具“note”(来自 App.js 状态)作为 axios 请求正文。
奇迹般有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.