简体   繁体   English

有人可以帮我在 v6 中使用 useEffect 挂钩修复 match.params.id 吗?

[英]Can someone please help me fix match.params.id using useEffect hook in v6?

Can someone please help me fix match.params.id using useEffect hook in v6?有人可以帮我在 v6 中使用 useEffect 挂钩修复 match.params.id 吗? I get a blank page when I do this so I need help.当我这样做时,我得到一个空白页,所以我需要帮助。 The code is below:代码如下:

import React, { Fragment, useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import { getProfileById } from '../../actions/profile';

const Profile = ({ getProfileById, profile: { profile, loading }, auth, match }) => {
  useEffect(() => {
    getProfileById(match.params.id);
  }, [getProfileById]);
  return (
  <div>profile</div>
  );
};

Profile.propTypes = {
    getProfileById: PropTypes.func.isRequired,
    profile: PropTypes.object.isRequired,
    auth: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
    profile: state.profile,
    auth: state.auth
});
export default connect(mapStateToProps, { getProfileById })(Profile);

In react-router-dom@6 there are not any route props, so there isn't any match prop.react-router-dom@6中没有任何路由道具,因此没有任何match道具。 Use the useParams hook to access the id route path param.使用useParams挂钩访问id路由路径参数。

import React, { Fragment, useEffect } from 'react';
import { useParams } from 'react-router-dom'; // (1) <-- import useParams hook
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import { getProfileById } from '../../actions/profile';

const Profile = ({ getProfileById, profile: { profile, loading }, auth }) => {
  const { id } = useParams(); // (2) <-- access id path param

  useEffect(() => {
    getProfileById(id); // (4) <-- pass to callback
  }, [getProfileById, id]); // (3) <-- add as dependency

  return (
    <div>profile</div>
  );
};

Profile.propTypes = {
  getProfileById: PropTypes.func.isRequired,
  profile: PropTypes.object.isRequired,
  auth: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
  profile: state.profile,
  auth: state.auth
});

export default connect(mapStateToProps, { getProfileById })(Profile);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM