在 React 中使用受保护的路由时无法读取未定义的属性“推送”

我正在尝试在我的仪表板中实施受保护的路由器。所以我的登陆页面直接是一个登录页面,如果用户成功登录,我想将页面重定向到我的仪表板。所以这是我的 index.js:

ReactDOM.render(
  <Router history={hist}>
    <Switch>
      <Route path="/" component={Login} exact />
      <ProtectedRoute path="/admin" component={(props) => <Adminlayout {...props} />}/>
      <Route path="" component={() => "404 NOT FOUND"} />
    </Switch>
  </Router>,document.getElementById("root")
);

所以我的登录组件非常基础,我在这里获取数据并检查用户是否存在于数据库中:

const Login = ({ submitForm },props) => {
  const [isSubmitted,setIsSubmitted] = useState(false);

  function submitForm() {
    setIsSubmitted(true);
  }
  const { handleChange,values,handleSubmit,errors } = useForm(
    submitForm,validate
  );

  const [loading,setLoading] = useState(false);
  const [error,setError] = useState(false);
  const [login,setLogin] = useState(false);

  const fetchLogin = async (email,password) => {
    try {
      setLoading(true);
      const res = await Axios({
          //API CALL
      });
      if (res.status === 200) {
        setLogin(true);
        localStorage.setItem("user-info",JSON.stringify(res));
      }
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  function loginButton() {
    fetchLogin(values.email,values.password);
    
    auth.login(() => {
      props.history.push("/admin");
    });
  }
  return (
    <form>
    </form>
  );
};

export default Login;

所以我有一个基本的 Auth 类:

class Auth {
    constructor() {
      this.authenticated = false;
    }
  
    login(cb) {
      this.authenticated = true;
      cb();
    }
  
    logout(cb) {
      this.authenticated = false;
      cb();
    }
  
    isAuthenticated() {
      return this.authenticated;
    }
  }
  
  export default new Auth();

这是我的受保护路由器:

export const ProtectedRoute = ({
  component: Component,...rest
}) => {
  return (
    <Route
      {...rest}
      render={props => {
        if (auth.isAuthenticated()) {
          return <Component {...props} />;
        } else {
          return (
            <Redirect
              to={{
                pathname: "/",state: {
                  from: props.location
                }
              }}
            />
          );
        }
      }}
    />
  );
};

所以一切看起来都很好,但是当我点击按钮提交时,我得到无法读取未定义的属性“推送”我真的不明白为什么我会得到它。

请查看我的代码并帮助我。 评论也是值得赞赏的。

henryin 回答:在 React 中使用受保护的路由时无法读取未定义的属性“推送”

好的,我认为问题在于您正在破坏道具并尝试使用默认值。

const Login = ({ submitForm },props) => {

你可以尝试将历史添加到你的解构列表中,还是相反地只使用道具而不解构进入你的组件的道具,然后再重组

const Login = ({ submitForm,history}) => { rest of your component...

or 

const Login = (props) => {
  const { submitForm,history } = props;
}

正如文档在我之前的评论中所说的那样,道具:匹配、位置和历史,在您在 Route 中使用它们时会自动传入

本文链接:https://www.f2er.com/201613.html

大家都在问