REACT ROUTER - Class 组件(仅) - 呈现页面 - JSON 文件

REACT ROUTER - Class component (only) - rendering page - JSON File

我正在研究 React 路由器项目(我是初学者)以提高我的技能。

我的问题:

我有一个JSON文件(龙珠Z)。当我点击角色(如悟空)时,我想展示他的传记。 实际上,当我点击悟空时,每个角色的传记都会显示出来。

我知道如何使用功能组件(useLocation 等..)来完成它,但我完全被 class 组件卡住了,因为我不能在其中使用挂钩,什么是好的方法它?

这是项目: DBZ REACT ROUTES

谢谢

使用 react-router-dom v6 我们可以使用 useParams 读取函数组件中的 params 键。 使用 class component 你可以写一个 HOC 函数来归档同样的东西

a higher-order component is a function that takes a component and returns a new component

import { useParams } from 'react-router-dom'

function withParams(Component) {
  return props => <Component {...props} params={useParams()} />;
}

class Charbio extends React.Component {
  componentDidMount() {
    let { id } = this.props.params;
    // get the bio by id here
  }

  render() {
    return API.map((element) => {
      return <p>{element.bio}</p>;
    });
  }
}

export default withParams(Charbio);