react router v6在 redux mapStateToProps函数中获取 url中params参数

在 v5 版本中,可用如下方法直接获取


const mapStateToProps = (state, ownProps) => {
  let params = ownProps.match.params;
  return {
    ...
  }
}

在v6版本中,需要通过useParams hook函数获取,但是如果直接在 mapStateToProps函数中使用,则会报错

import { useParams } from "react-router-dom"
const mapStateToProps = (state, ownProps) => {
  console.log(useParams())
  return {
     ...
  }
}

React Hook "useParams" is called in function "mapStateToProps" that is neither a React function component nor a custom React Hook function.

这时候我们需要自定义一个 WithRouter(不同于v5 版本的 withRouter) 的高阶组件,

import { useParams, useLocation } from "react-router-dom"

export default function WithRouter(Child) {
  return function WithRouter(props) {
    const params = useParams();
    const location = useLocation();
    return <Child {...props} params={params} location={location} />
  }
}

post.js 文件

import React, { Component } from "react";
import { connect } from 'react-redux';
import WithRouter from '../hoc/WithRouter';

class Post extends Component {
  render() {
    return (
      <div className="container">
        {this.props.post ? (
          <div className="post">
            <h4 className="center">{ this.props.post.title }</h4>
            <p>{ this.props.post.body }</p>
          </div>
        ) : (
          <div className="container">文章正在加载...</div>
        )}
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps);
  let id = ownProps.params.post_id;
  return {
    post: state.posts.find(post => post.id == id)
  }
}

export default WithRouter(connect(mapStateToProps)(Post));

ownProps打印如下

 这样,在mapStateToProps函数中就可以获取到对应的 路由中的参数,然后去做相应的逻辑处理。

猜你喜欢

转载自blog.csdn.net/longgege001/article/details/123428358