【问题标题】:TypeError: history.push is not a function: How can I fix this?TypeError:history.push 不是函数:我该如何解决这个问题?
【发布时间】:2021-09-15 02:40:32
【问题描述】:

我有这两个表单,我想在第一个表单提交handleSubmit 后将用户重定向到主页。我已经声明了withRouter 并使用了它。但是,它仍然有错误:

TypeError:history.push 不是函数

以下是代码:

import { withRouter } from "react-router-dom";


import firebase from "firebase/app";

const Session = ({ id }) => {
  const classes = useStyles();

  ....other codes above

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore.collection("users").doc(id);
      const ref = userRef.set(
        {
          items: {
            id,
            ...variable names here
          },
        },

        { merge: true }
      );

      console.log(" saved");
      stocksCounter();
      history.push("/");  <-- history.push
    } catch (err) {
      console.log(err);
    }
  };

  

  //2nd submit-----------------------------------------------------------
  ...other codes here
  const handleSubmit2 = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore.collection("users").doc(scanResult);
      const ref = userRef.set(
        {
          items: {
           ..variable names here
          },
        },
        { merge: true }
      );

      console.log(" saved");
      stocksCounter();
    } catch (err) {
      console.log(err);
    }
  };

  return (
  ....codes here
  );
};

export default withRouter(Session);

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    虽然有一个全局历史对象,但您需要使用 props.history 的 react-router 中的历史记录,该历史记录是使用 withRouter 注入的

    【讨论】:

      【解决方案2】:

      使用useHistory 钩子。

      const history = useHistory();
      history.push('/')
      

      【讨论】:

        【解决方案3】:

        首先从 react 导入 useHistory 然后在handleSubmit里面添加 const history = useHistory() 最后 history.push('/') - 路由器

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。
        猜你喜欢
        • 1970-01-01
        • 2021-04-13
        • 2019-02-08
        • 2020-03-25
        • 2020-02-14
        • 2021-10-23
        相关资源
        最近更新 更多