首页 > 解决方案 > 使用 MapStateToProps 时未定义 props

问题描述

当我到达我的主页时,我的当前状态是一个由我的文章对象组成的对象。

articles:
0: {id:'3',body:'ballon pied ball…football'}
1: {id:'2',body:'Encore du Lorem … article'}
2: {id:'1',body:'Lorem Ipsum Dolo… article'}

对应首页文章列表;当我点击其中一个时,它应该将我重定向到我可以阅读的文章的特定页面。(/article/:id)

所以我尝试创建一个 Article 组件来呈现它的标题、副标题和正文。但我得到“道具未定义”作为错误:

Article.js零件:

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


const Article = ({match}) => (
<div className="aboutpage-wrapper">
  <div className="container">
    <h1>{match.params.id}</h1>
    {console.log(props)}
{/*    <h2>{props.article.title}</h2>
    <h3>{props.article.subtitle}</h3>
    <p>{props.article.body}</p>*/}
  </div>
</div>
);

const mapStateToProps = state => ({ article: state.articles[1] });
// I try to access articles[1] just to see if it works.

export default connect(mapStateToProps)(Article);

任何想法 ?

标签: reactjsreduxreact-redux

解决方案


这是因为在您的 Article 组件中您解构了 props: ({ match }),因此您将无法访问props.

如果你想props直接在你的文章组件中访问,那么你应该这样做:

const Article = props => (...);

如果要继续解构 props,则列出所有需要的 props 字段,如下所示:

const Article = ({ match, article, ...rest }) => (...);

推荐阅读