如何在reactJS中使用SubmitHandler导航到另一个页面?



我想在提交详细信息后立即导航到仪表板页面。这里是我的CreateMonthWallet类,我在不同的月份创建不同的。在这个创建表单中,用户需要收集的所有信息都在那里。一旦用户单击create按钮,用户应该导航回Dashboard页面。下面给出的是CreateMonthWallet类的代码。当我运行代码时,一旦单击cleate按钮,它就会给我错误消息,但数据更新到数据库,但仍然在本地主机页面上显示错误消息,并且不会导航到仪表板。

import axios from 'axios'
import React, { Component } from 'react'
class CreateMonthWallet extends Component {
constructor(props) {
super(props)
this.state = {
name: '',
accountNumber: '',
description: '',
priority: ''
}
}
changeHandler = (event, fieldName) => {
this.setState({
[fieldName]: event.target.value
})
}
submitHandler = (event) => {
const newWallet = {
name: this.state.name,
accountNumber: this.state.accountNumber,
description: this.state.description,
priority: this.state.priority
}
axios.post('http://localhost:8080/monthwallet', newWallet)
.then((res) => {
this.props.history.push('/Dashboard')
}).catch((err) => {
alert("Error")
})
event.preventDefault()
}
render() {
return (
<div className="project">
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<h5 className="display-4 text-center">Create Wallet</h5>
<hr />
<form onSubmit={(event)=>this.submitHandler(event)}>
<div className="form-group">
<input type="text" onChange={(event) => this.changeHandler(event, "name")} className="form-control form-control-lg " placeholder="Account Name" />
</div>
<div className="form-group">
<input type="text" onChange={(event) => this.changeHandler(event, "accountNumber")} className="form-control form-control-lg" placeholder="Account No" />
</div>
<div className="form-group">
<textarea onChange={(event) => this.changeHandler(event, "description")} className="form-control form-control-lg" placeholder="Description"></textarea>
</div>
<div className="form-group">
<select className="form-control form-control-lg" onChange={(event) => this.changeHandler(event, "priority")}>
<option value={3}>Display Priority</option>
<option value={1}>High</option>
<option value={2}>Medium</option>
<option value={3}>Low</option>
</select>
</div>
<input type="submit" className="btn btn-dark btn-block mt-4" value="Create" />
</form>
</div>
</div>
</div>
</div>
)
}
}
export default CreateMonthWallet

编辑:将功能App的内容添加到问题中。

function App() {
return (
<Router>
<div>
<Nav />
<Routes>
<Route path="/" element={<Welcome />} exact />
<Route path="/Dashboard" element={<Dashboard />} exact />
<Route path="/CreateMonthWallet" element={<CreateMonthWallet />} exact />
<Route path="*" element={<NotFound />} exact />
</Routes>
</div>
</Router>
)
}

Issue

react-router-dom@6删除了路由道具,所以当尝试执行this.props.history.push('/Dashboard')时,控制台应该有一些can't access property "push" of undefined的错误。对象historynavigate函数取代在RRDv6中,通过useNavigate钩子访问。

<标题>

解决方案你可以将CreateMonthWallet转换成一个React函数组件,这样它就可以使用React钩子,或者你可以创建一个自定义的withRouterhigh Order组件来注入navigate函数作为prop。

转换为React函数组件

import axios from 'axios'
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
const CreateMonthWallet  = () => {
const navigate = useNavigate();
const [state, setState] = useState({
name: '',
accountNumber: '',
description: '',
priority: ''
});
const changeHandler = (event) => {
const { name, value } = event.target;
setState(state => ({
...state,
[name]: value
}))
}
const submitHandler = (event) => {
event.preventDefault();
axios.post('http://localhost:8080/monthwallet', state)
.then((res) => {
navigate('/Dashboard');
})
.catch((err) => {
alert("Error");
});
}
return (
<div className="project">
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<h5 className="display-4 text-center">Create Wallet</h5>
<hr />
<form onSubmit={submitHandler}>
<div className="form-group">
<input
type="text"
name="name"
onChange={changeHandler}
className="form-control form-control-lg"
placeholder="Account Name"
value={state.name}
/>
</div>
<div className="form-group">
<input
type="text"
name="accountNumber"
onChange={changeHandler}
className="form-control form-control-lg"
placeholder="Account No"
value={state.accountNumber}
/>
</div>
<div className="form-group">
<textarea
name="description"
onChange={changeHandler}
className="form-control form-control-lg"
placeholder="Description"
value={state.description}
/>
</div>
<div className="form-group">
<select
className="form-control form-control-lg"
name="priority"
onChange={changeHandler}
value={state.priority}
>
<option value={3}>Display Priority</option>
<option value={1}>High</option>
<option value={2}>Medium</option>
<option value={3}>Low</option>
</select>
</div>
<input
type="submit"
className="btn btn-dark btn-block mt-4" value="Create"
/>
</form>
</div>
</div>
</div>
</div>
);
};
export default CreateMonthWallet;

创建withRouterHOC

按照What happened to withouter ?我需要它!创建一个替代withRouterHOC。

的例子:

import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
const withRouter = Component => props => {
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}

用新的withRouterHOC装饰CreateMonthWallet并访问this.props.router.navigate

class CreateMonthWallet extends Component {
...
submitHandler = (event) => {
event.preventDefault();
const newWallet = { ...this.state };
axios.post('http://localhost:8080/monthwallet', newWallet)
.then((res) => {
this.props.router.navigate('/Dashboard');
})
.catch((err) => {
alert("Error")
});
}
render() {
return (
...
);
}
}
export default withRouter(CreateMonthWallet);

看起来您还没有创建历史变量。这是小菜一碟。

这个你要创建的变量,命名为history,将负责在你的应用程序中存储你的浏览历史。

例如,通过历史记录,您可以获得goBack()的能力。注意,react-router现在更倾向于导航。您可以查看下面的链接,以便稍后升级到新版本。

react-router返回页面如何配置历史记录?

让我们把问题留在这里。

import {BrowserRouter, } from "react-router-dom";
import { createBrowserHistory } from 'history';

function App() {
const history = createBrowserHistory() //creates the variable history
return (
<BrowserRouter>
<div>
<Nav />
<Routes>
<Route path="/" element={<Welcome />} exact />
<Route path="/dashboard" element={<Dashboard history={history}/>} exact /> //passes it down to child component
<Route path="/createmonthwallet" element={<CreateMonthWallet history={history}/>} exact /> //passes it down to child component
<Route path="*" element={<NotFound />} exact />
</Routes>
</div>
</BrowserRouter>
)
}

我们在这里做了什么:

  1. 通过从历史中导入createBrowserHistory创建一个历史对象。如果你还没有,可以使用'npm install history'。
  2. 在你的App函数中定义变量
  3. 将它作为'props'在你的Route中传递。

现在,你的组件将可以访问this.props.history,错误应该会消失。

作为旁注,最好在代码的任何地方使用函数组件。更容易读,更容易写,更灵活。另外,避免在path中使用大写字母。比如path="wallet/month/create"从长远来看会看起来更优雅,因为你可以有&;wallet/month/update&; &;wallet/month/delete&;等等

相关内容

  • 没有找到相关文章

最新更新