Error:"Expected an assignment or function call and instead saw an expression" in the component which implements user registration.Why?

Error:"Expected an assignment or function call and instead saw an expression" in the component which implements user registration.Why?

我需要在我的应用程序中实现 registerauthorize

目前,我已经实现了这个:

小部分SignupForm.js(修改前,工作正常):

const SignupForm = () => {

    const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({  
      initialValues: {
         /.......
      },
        validateOnBlur: false, 
        validateOnchange: false,
        validationSchema: yup.object().shape({    
          /.......
      }),   
      onSubmit: async (formValues) => {
          console.log('submit', formValues);
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              const token = res.token.token;
              localStorage.setItem('myToken', token);
              console.log('Result!',token);
          } catch(e) {
              console.error(e);   
          } finally {
              setSubmitting(false);
          }   
      },  
    });

   return (
   <form className="fform" onSubmit={handleSubmit}>   
       /........
       <button type="submit" disabled={isSubmitting}>Submit Form</button>       
   </form>
   );
};

但我还需要这样做:

我决定以这种方式实现它(我注释了我添加的行,以及错误所在的行):

const SignupForm = () => {

    const [myToken, setMyToken] = useState(         // add this line
       localStorage.getItem("myToken")              // add this line
    );


    myToken ? <Redirect to="/home" /> : <Redirect to="/" />  // add this line.I have error here

    const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({  
      initialValues: {
         /.......
      },
        validateOnBlur: false, 
        validateOnchange: false,
        validationSchema: yup.object().shape({    
          /.......
      }),   
      onSubmit: async (formValues) => {
          console.log('submit', formValues);
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              const token = res.token.token;
              localStorage.setItem('myToken', token);
              console.log('Result!',token);
          } catch(e) {
              console.error(e);   
          } finally {
              setSubmitting(false);
          }   
      },  
    });

   return (
   <form className="fform" onSubmit={handleSubmit}>   
       /........
       <button type="submit" disabled={isSubmitting}>Submit Form</button>       
   </form>
   );
};

我有错误:

Expected an assignment or function call and instead saw an expression

你应该如何编写代码来防止这样的错误?

另外我会写sandbox项目之前的变化:

https://codesandbox.io/s/flamboyant-neumann-hwj1t

在文件夹 public/data 的沙箱中我创建了文件 data.json 因为我在我的计算机中使用本地服务器并且无法将数据从本地服务器传输到沙箱

为了以编程方式使用 React Router 进行重定向,您必须使用特殊功能,而不是组件:

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

const SignupForm = () => {
    const history = useHistory();

    const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({  
      initialValues: {
         /.......
      },
        validateOnBlur: false, 
        validateOnchange: false,
        validationSchema: yup.object().shape({    
          /.......
      }),   
      onSubmit: async (formValues) => {
          console.log('submit', formValues);
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              const token = res.token.token;
              localStorage.setItem('myToken', token);
              console.log('Result!',token);

              history.push("/home");  //redirect
          } catch(e) {
              console.error(e);   
          } finally {
              setSubmitting(false);
          }   
      },  
    });

   return (
   <form className="fform" onSubmit={handleSubmit}>   
       /........
       <button type="submit" disabled={isSubmitting}>Submit Form</button>       
   </form>
   );
};

您可以在所有其他需要更改 url 的地方执行此类重定向。

以下是如何实现“/home”来重定向未授权用户。

const Home = () => {
    const token = localStorage.getItem("myToken")

    return (
        <>
            {!token && <Redirect to="/" />}
            <p>Home page</p>
        </>
    )
}

我想你想做的是这个:

import { useHistory } from 'react-router-dom';

const SignupForm = () => {
    const [myToken, setMyToken] = useState(localStorage.getItem("myToken"));
    const redirectUrl = myToken ? '/home' : '/'; // Updated this line

    const { handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting } = useFormik({  
      initialValues: {
        /.......
      },
      validateOnBlur: false, 
      validateOnChange: false,
      validationSchema: yup.object().shape({    
          /.......
      }),   
      onSubmit: async (formValues) => {
          console.log('submit', formValues);
          setSubmitting(true);
          try {
              const res = await api('api/auth/register', {
                  method:'POST',
                  body: JSON.stringify(formValues)
              });
              const token = res.token.token;
              localStorage.setItem('myToken', token);
              history.push(redirectUrl);  // Redirect to appropriate route path
          } catch(e) {
              console.error(e);   
          } finally {
              setSubmitting(false);
          }   
      },  
    });

   return (
     <form className="form" onSubmit={handleSubmit}>   
       /........
       <button type="submit" disabled={isSubmitting}>Submit Form</button>       
     </form>
   );
};

上面我设置了一个变量 redirectUrl,它将保存根据令牌的可用性重定向到的路径。然后稍后使用 useHistory 挂钩中的 history.push 从先前分配的变量重定向到 url。