簡體   English   中英

有人可以幫我在 v6 中使用 useEffect 掛鈎修復 match.params.id 嗎?

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

有人可以幫我在 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM