搜尋

首頁  >  問答  >  主體

以程式設計方式重新導向到React Router v6中的路由時出現問題

我想對某些使用者操作執行導航,例如按鈕的 onSubmit。假設使用者點擊「新增聯絡人」按鈕,我希望反應路由器在主頁「/」中重定向。目前我面臨這個問題--> TypeError: Cannot readproperties of undefined (reading 'push').作為初學者,我非常感謝專家的幫助。

AddContacts.js

import React, { Component } from "react";
import { Consumer } from "../../context";
import TextInputGroup from "../layout/TextInputGroup";
import { v4 as uuidv4 } from "uuid";
import { useNavigate } from "react-router-dom";

class AddContacts extends Component {
  state = {
    name: "",
    email: "",
    phone: "",
    errors: {},
  };
  onSubmit = (dispatch, e) => {
    e.preventDefault();

    const { name, email, phone } = this.state;

    //Check for errors

    if (name === "") {
      this.setState({ errors: { name: "Name is required" } });
      return;
    }
    if (email === "") {
      this.setState({ errors: { email: "Email is required" } });
      return;
    }
    if (phone === "") {
      this.setState({ errors: { phone: "Phone is required" } });
      return;
    }

    const newContact = {
      id: uuidv4(),
      name,
      email,
      phone,
    };
    dispatch({ type: "ADD_CONTACT", payload: newContact });

    this.setState({
      name: "",
      email: "",
      phone: "",
      errors: {},
    });
    this.props.navigate.push("/");
  };

  onChange = (e) => this.setState({ [e.target.name]: e.target.value });
  render() {
    const { name, email, phone, errors } = this.state;

    return (
      <Consumer>
        {(value) => {
          const { dispatch } = value;

          return (
            <div className="card mb-3">
              <div className="card-header">Add Contacts</div>
              <div className="card-body">
                <form onSubmit={this.onSubmit.bind(this, dispatch)}>
                  <TextInputGroup
                    label="Name"
                    name="name"
                    placeholder="Enter Name..."
                    value={name}
                    onChange={this.onChange}
                    error={errors.name}
                  />
                  <TextInputGroup
                    label="Email"
                    name="email"
                    type="email"
                    placeholder="Enter Email..."
                    value={email}
                    onChange={this.onChange}
                    error={errors.email}
                  />
                  <TextInputGroup
                    label="Phone"
                    name="phone"
                    placeholder="Enter Phone..."
                    value={phone}
                    onChange={this.onChange}
                    error={errors.phone}
                  />
                  <input
                    type="submit"
                    value="Add Contact"
                    className="btn btn-light btn-block mt-3"
                  />
                </form>
              </div>
            </div>
          );
        }}
      </Consumer>
    );
  }
}

export default AddContacts;

這是 App.js 檔案

import React, { Component } from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

import Contacts from "./components/contacts/Contacts";
import Header from "./components/layout/Header";
import AddContacts from "./components/contacts/AddContacts";
import About from "./components/pages/About";

import { Provider } from "./context";

import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

function App() {
  return (
    <Provider>
      <BrowserRouter>
        <div className="App">
          <Header branding="Contact manager" />
          <div className="container">
            <Routes>
              <Route path="/" element={<Contacts />} />{" "}
              <Route path="/contact/add/*" element={<AddContacts />} />{" "}
              <Route path="about/*" element={<About />} />{" "}
            </Routes>{" "}
          </div>{" "}
        </div>{" "}
      </BrowserRouter>{" "}
    </Provider>
  );
}

export default App;


#
P粉693126115P粉693126115396 天前647

全部回覆(2)我來回復

  • P粉905144514

    P粉9051445142023-10-31 19:13:17

    如何在 React Router v6 中重定向

    #
    import {  useNavigate  } from "react-router-dom";
    
      const navigate = useNavigate();
      
      const handleClick = () => {
        navigate("/dashboard");
      };

    回覆
    0
  • P粉384244473

    P粉3842444732023-10-31 13:19:10

    問題

    這是因為您嘗試從不存在的 navigate 屬性進行導航,它是未定義的。

    this.props.navigate.push("/");

    useNavigate 掛鉤僅與函數元件相容,因此如果您想要/需要將navigate 與類別元件一起使用,則必須轉換AddContacts 到函數元件,或捲動您自己的自訂withRouter 高階元件來注入“路由道具”,例如來自react-router-dom 的withRouter HOC v5. x 做到了。

    解決方案

    我不會介紹如何將類別元件轉換為函數元件。下面是一個自訂 withRouter HOC 範例:

    const withRouter = WrappedComponent => props => {
      const navigate = useNavigate();
      // etc... other react-router-dom v6 hooks
    
      return (
        <WrappedComponent
          {...props}
          navigate={navigate}
          // etc...
        />
      );
    };

    並使用新的 HOC 裝飾 AddContacts 元件。

    export default withRouter(AddContacts);

    現在會將 navigate 屬性(以及您設定的任何其他屬性)傳遞給裝飾元件,並且 this.navigate 現在將已定義。

    此外,導覽 API 從 v5 變更為 v6,不再使用直接的 history 物件。 navigate 是一個函數而不是一個物件。要使用您呼叫函數並傳遞1 或2 個參數,第一個是目標路徑,第二個是帶有replace 和/或state 鍵的可選“選項”物件/值。

    現在導航如下:

    this.props.navigate("/");

    回覆
    0
  • 取消回覆