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 
  }
}

post.js 文件

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

class Post extends Component {
  render() {
    return (
      
{this.props.post ? (

{ this.props.post.title }

{ this.props.post.body }

) : (
文章正在加载...
)}
) } } 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打印如下

react router v6在 redux mapStateToProps函数中获取 url中params参数_第1张图片

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

你可能感兴趣的:(react,react.js,javascript,useParams,redux)