如何在v6中使用useEffect钩子修复match.params.id



如何在v6中使用useEffect钩子修复match.params.id?当我这样做的时候,我会得到一张空白页。代码如下:

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);

react-router-dom@6中没有任何路由道具,因此没有任何match道具。使用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);

最新更新