从重定向中获取 mapStateToProps 中的 ownProps.match.params.id

Get ownProps.match.params.id in mapStateToProps from Redirect

卡片组件显示文章数据或笔记数据。

我想在 Card 组件中点击 Link 后继续查看卡片详细信息,并在 Details 组件中显示它们,所以我使用了重定向,如下所示:

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import Link from 'components/atoms/Link/Link';

class Card extends Component {
  state = { redirect: false };
  toggleButtonDetails = () => this.setState({ redirect: true });

  render() {
    const { _id, type } = this.props;
    const { redirect } = this.state;

    if (redirect) {
      return <Redirect push to={`/${type}/${_id}`} />;
    }

    return (
      <Link onClick={this.toggleButtonDetails}>See details</Link>
    );
  }
}

export default Card;

这很重要,因为我不想在 URL 发送 notes\:id 请求或 articles\:id 请求(在浏览器中输入)的基础上获取详细信息,而是从存储位置有很多文章和笔记。

所以,我决定在 Details 组件中使用 ownProps in mapStateToProps

import React from 'react';
import { connect } from 'react-redux';

const Details = ({ activeItem }) => {
  const [item] = activeItem;
  return (
    <>
      <p>{item.id}</p>
      <p>{item.type}</p>
    </>
  );
};

const mapStateToProps = (state, ownProps) => ({
  activeItem: state[ownProps.type].filter(item => item._id === ownProps.match.params.id),
});

export default connect(mapStateToProps)(Details);

单击 Card 中的 Link 后,我移动到更正 URL(例如 http://localhost:3000/notes/5d3c87034532003a6c666a67),但出现错误,我得到 Cannot read property 'params' of undefined 符合 activeItem: state[ownProps.type]....

当我在 mapStateToProps 中使用 console.log(ownProps) 时,我看到 ownProps 只包含 type 而没有 id.

当我将 ownProps.match.params.id 更改为 '5d3c87034532003a6c666a67' 时,我看到了正确的注释详细信息,但只有一个指定的注释 - 这很明显,但这意味着 store 工作正常,但我没有看到id 属性 在 Details 组件.

编辑:Details 组件位于 Article 组件内部并且没有 id...

const Article = () => (
  <Online>
    <Wrapper>
      <Header>Your article</Header>
      <Details type="articles" />
    </Wrapper>
  </Online>
);

export default Article;

应该是通过这个的方法id属性...我离解决方案更近了...

Details component is located inside Article component and there is no id...

嗯,你是对的。 Details 永远得不到 match 属性。您需要使用 withRouter HOC。

export default connect(mapStateToProps)(withRouter(Details))

或者(不推荐)从Article

钻道具
const Article = (props) => (
  <Online>
    <Wrapper>
      <Header>Your article</Header>
      <Details type="articles" {...props} />
    </Wrapper>
  </Online>
);