簡體   English   中英

當第二個 history.push 被觸發時,react-router-dom 返回 undefined

[英]react-router-dom return undefined when second history.push is triggered

您好,有以下 Antd 模式:

<Modal visible={visible} onOk={handleOk} onCancel={handleCancel}>
  <MyForm onSubmit={handleOpenUrl}>
      <CustomInput
        name="input"
        onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
          handleInput(event, "input")
        }
      />
      <Button type="submit" >
        Submit
      </Button>
  </MyForm>
</Modal>;

我有這個表單的以下處理程序:

const handleInput = (event: React.SyntheticEvent) => {
  event.preventDefault();
  // other operation where checked is handled...
  history.push({
    pathname: "/",
    search: "?" + new URLSearchParams({ datas: checked }).toString(),
  });
};

奇怪的是,當我打開表單並第一次提交表單時,它會更新 url 並將其添加如下: http://localhost:3000/?datas=myqueryparams但是當我第二次這樣做時它說的時間:類型錯誤TypeError: Cannot read properties of undefined (reading 'push')

對此有什么想法嗎?

更新

對於 app 組件,我添加了以下內容:

<Switch>
          <Route path="/?datas=:datas" exact component={App} />
          <Route path="/" exact component={App} />
        </Switch>

您是否使用 react-router-dom 中的BrowserRouter包裝了應用程序組件? 像這樣的示例代碼

import React from "react";
import {
  BrowserRouter as Router
} from "react-router-dom";

export default function App() {
  return (
    <Router>
     <ChildComponent />
    </Router>
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM