即时使用react-reactx和react-router进行反应。我正在我的博客上工作,其中我有一个显示帖子列表的组件。所以一切都工作正常但是当我在组件中得到post.id时它给了我undefined。另一方面,帖子从容器传递给组件。 请查看我的代码。
//home_container.js
import { connect } from 'react-redux'
import { show } from './actions'
import HomeComponent from './home_component'
const mapStateToProps = (state) => {
return {
posts: state.posts.data
}
}
const mapDispatchToProps = (dispatch) => {
return {
actions:{
showPosts: (page,limit) => {
show(dispatch,page,limit)
}
}
}
}
const HomeContainer = connect(
mapStateToProps,
mapDispatchToProps
)(HomeComponent)
export default HomeContainer
// home_component.js文件
import React, {Component} from 'react';
import Paper from 'material-ui/Paper';
import Style from './styles.css'
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router'
require('rc-pagination/assets/index.css');
const Pagination = require('rc-pagination');
const style = {
height: "100%",
margin: 10,
padding: 10,
display: 'inline-block',
};
var Detail = React.createClass({
render: function() {
return (
<div >
<div className="row">
<div >
<p>{this.props.post?this.props.post.body.substr(1,600):''}</p>
{this.props.post?
<span style={{"float":"right"}}>
<Link to={`/posts/${this.props.post.id}`}>
<FlatButton
label="Ready more"
labelPosition="before"
primary={true}
/>
</Link>
</span>
:''}
</div>
</div>
</div>
)
}
});
class Index extends Component {
getChildContext() {
return { muiTheme: getMuiTheme(baseTheme) };
}
componentDidMount(){
this.props.actions.showPosts(1,5)
}
render() {
return (
<div >
{this.props.posts.map((post,i) =>
<div className="row" key={i}>
<Paper
style={style}
zDepth={0}
children={<Detail post={post}/>}
/>
)}
</div>
);
}
}
Index.childContextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
export default Index;
我已经通过react-redux检查员检查了一下。我在这个组件的帖子道具中有帖子,这些帖子是由容器通过react redux设置的。 所以问题出现在上面代码的以下部分。
<Link to={`/posts/${this.props.post.id}`}>
<FlatButton
label="Ready more"
labelPosition="before"
primary={true}
/>
</Link>
以反应路由器的标签链接生成此表单中的url posts / undefined。因为它正在考虑post.id未定义。另一方面,每个帖子都有id属性,我也通过检查帖子对象来检查它。
因此问题出现在这一行this.props.post.id