reactjs - 使用 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);
任何想法 ?
解决方案
这是因为在您的 Article 组件中您解构了 props: ({ match })
,因此您将无法访问props
.
如果你想props
直接在你的文章组件中访问,那么你应该这样做:
const Article = props => (...);
如果要继续解构 props,则列出所有需要的 props 字段,如下所示:
const Article = ({ match, article, ...rest }) => (...);
推荐阅读
- javascript - 注册 ServiceWorker 失败
- python - Xgboost:如何在 Dmatrix 中制作一个 CSV 到一个标签
- firebase - 如何解决flutter中的内部错误以使用firebase_auth
- python - 如何在 python turtle 中添加两个或更多按钮
- mysql - DROP CONSTRAINT 无法找到约束
- matlab - 随机脉冲发生器问题
- php - Python Imports 不会在 PHP 中给出输出
- matlab - 在 Matlab (Ubuntu) 上下载/安装 Psychtoolbox 的问题
- c - LibHaru C Windows 安装问题
- android - 有没有办法让 EditText 始终处于焦点而不触碰?