reactjs 如何使用React从URL获取参数?

jdzmm42g  于 2022-12-12  发布在  React
关注(0)|答案(3)|浏览(143)

我正在尝试使用react设置验证帐户,并且在我的App.js文件中有以下内容
App.js

import SigninPage from './pages/signin';
import ResetPasswordPage from './pages/resetPassword'
import VerifyAccountPage from './pages/verifyAccount'
...
...
import { useHistory } from 'react-router';
import { logout } from './utils/auth';

function App() {

  const history = useHistory();
  
  return (
    <Router>
      <Switch>
        <Route path='/' component={Home} exact />
        <Route
            path="/signout"
            render={() => {
              logout();
              history.push('/');
              return null;
            }}
        />
        <Route path='/signin' component={SigninPage} exact />
        <Route path='/reset-password?reset-password-token=:resetPasswordToken' component={ResetPasswordPage} />
        <Route path='/verify-account?token=:token&email=:email' component={VerifyAccountPage} exact />
      </Switch>
    </Router>
  );
}

export default App;

并且在我的VerifyAccountPage组件中具有以下内容

import { Redirect } from 'react-router-dom';
import { useHistory } from 'react-router';
import { verifyAccount, isAuthenticated } from '../../utils/auth';

const VerifyAccount = () => {

  const { token, email } = this.props.match.params
  const history = useHistory();
  const [error, setError] = useState('');

  const handleGet = async (e) => {
    e.preventDefault();
    setError('');
    try {
      const data = await verifyAccount(token, email);

      if (data) {
        history.push('/');
      }
      console.log(data);
    } catch (err) {
      if (err instanceof Error) {
        // handle errors thrown from frontend
        setError(err.message);
      } else {
        // handle errors thrown from backend
        setError(err);
      }
    }
  };

  return isAuthenticated() ? (
    <Redirect to="/#" />
    ) : (  
    <>
      <Container>
        <FormWrap>
          <Icon to='/'>mywebsite</Icon>
          <FormContent>
            <Form action='#'>
              <FormH1>Verify Account</FormH1>
              <Text>Account has been verified!</Text>
            </Form>
          </FormContent>
        </FormWrap>
      </Container>
    </>
  );
};

export default VerifyAccount;

这是verifyAccount.js

import React from 'react';
import VerifyAccount from '../components/VerifyAccount';
import ScrollToTop from '../components/ScrollToTop';

function VerifyAccountPage() {
  return (
    <>
      <ScrollToTop />
      <VerifyAccount />
    </>
  );
}

export default VerifyAccountPage;

这里是
index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

但这不起作用,当我转到链接https://mywebsite.com/verify-account?token=3heubek&email=user1@email.com时,除了200或304状态代码外,什么也没发生
没有向API发送请求,因此意味着未提取参数
谁能告诉我发生了什么事?
package.json文件中使用的软件包版本

"dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-icons": "^3.11.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    "react-scroll": "^1.8.1",
    "styled-components": "^5.2.0",
    "@types/node": "^15.6.0",
    "jwt-decode": "^3.0.0"
xjreopfe

xjreopfe1#

路由匹配参数与URL查询字符串参数不同。
您将需要从location对象访问查询字符串。

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string', <-- query string
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}

React-router-dom query parameters demo
它们创建一个自定义的useQuery钩子:

const useQuery = () => new URLSearchParams(useLocation().search);

对于您的用例,在呈现VerifyAccountPage的页面上,您希望提取查询字符串参数。

const query = useQuery();

const email = query.get('email');
const token = query.get('token');

基于类的组件?

如果VerifyAccountPage是一个基于类的组件,那么你需要访问props.location并在生命周期方法中自己处理查询字符串,这是因为React钩子只被功能组件有效使用。

componentDidMount() {
  const { location } = this.props;
  const query = new URLSearchParams(location.search);
  
  const email = query.get('email');
  const token = query.get('token');
  ...
}
关于路径的注解
path='/verify-account?token=:token&email=:email'

路径参数只在URL的path部分相关,你不能为URL的queryString部分定义参数。从react-router-dom的Angular 来看,上面的路径等价于path='/verify-account'

0x6upsns

0x6upsns2#

您可以使用withRouter获取路由器信息,如位置、历史记录、路径和参数。

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

...

const VerifyAccount = withRouter(props) => {
  const { token, email } = props.match.params;
  console.log("toke, email: ", token, email)     // And also show me how it looks!!!
  ...
}

你应该这样定义你的路线。

<Route path='/verify-account/:token/:email' component={VerifyAccountPage} />

你应该这样叫:

https://your-domain/verify-account/[token]/[email]

这样就行了

ukxgm1gy

ukxgm1gy3#

ReactJS

第一个

普通JavaScript

const siteUrl = window.location.search;
const urlParams = new URLSearchParams(siteUrl);
console.log( urlParams['id'] ) // 159

相关问题