如何使用React将应用程序从表单路由回到首页?

我对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文件,以便更好地了解发生了什么,并注释掉似乎不必要的内容。

climb166 回答:如何使用React将应用程序从表单路由回到首页?

我不知道App.js的导出方法,但是如果不使用withRouter导出组件,则可能无法使用历史记录道具。

一个简单的解决方案是只使用window.location = '/';而不是history.push()

,

感谢@seanulus解决此问题的正确方法。

我的handleSubmit函数只需要存在于NoteEdit.js组件中,并使用prop'note'(来自App.js状态)作为axios请求主体。

像魅力一样工作!

本文链接:https://www.f2er.com/3114307.html

大家都在问