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

6tqwzwtp  于 2022-12-29  发布在  React
关注(0)|答案(2)|浏览(198)

我想在提交详细信息后立即导航到 Jmeter 板页面。这是我的CreateMonthWallet类,我在其中为不同月份创建不同的类。在此创建表单中,包含用户需要收集的所有信息。用户单击“创建”按钮后,用户应该导航回 Jmeter 板页面。2下面给出的是CreateMonthWallet类的代码。3当我运行代码时,一旦点击cleate按钮后,它给我错误的消息,但数据更新到数据库,但仍然显示在localhost页面上的错误消息,不导航到 Jmeter 板.

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
oymdgrw7

oymdgrw71#

看起来您还没有创建历史变量。这是小菜一碟。
您要创建的变量名为history,它将负责存储您在应用中的浏览历史记录。
例如,使用历史记录你可以获得goBack()的能力,注意react-router现在更倾向于导航,你可以稍后查看下面的链接升级到新版本。
react-router go back a page how do you configure history?
但我们还是继续讨论这个问题吧。

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安装历史记录”。
1.在App函数内定义变量。
1.把它作为你路线中的“ prop ”传递下去。
现在,您的组件将可以访问这个.props.history,而您的错误应该会消失。
如sidealines所示,最好使用代码中的任何函数组件。更容易读、写,也更灵活。另外,避免在path中使用大写字母。像path=“wallet/month/create”这样的东西从长远来看会看起来更优雅,因为你可以使用“wallet/month/update”、“wallet/month/delete”等等

b91juud3

b91juud32#

问题

react-router-dom@6删除了路由属性,因此在尝试执行this.props.history.push('/Dashboard')时,控制台中应该会出现类似can't access property "push" of undefined的错误。在RRDv6中,history***对象***被navigate*函数替换,可通过useNavigate挂钩访问。

溶液

您可以将CreateMonthWallet转换为React函数组件,这样它就可以使用React钩子,或者您可以创建一个定制的withRouter高阶组件,将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;

创建withRouter HOC

按照RRDV6常见问题解答的一部分中WithRouter发生了什么?我需要它!的说明创建一个替换的withRouter HOC。
示例:

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 }}
    />
  );
}

使用新的withRouter HOC装饰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);

相关问题