【发布时间】:2018-05-22 04:12:43
【问题描述】:
我正在尝试通过添加来自父级的道具来使此帖子组件可重用。我的道具是“路径名”和“过滤器”。我有一个我想要更新的数据库的路径名和一个过滤器,它允许我从该数据库中过滤掉数据。它根据路径名和过滤器打印出帖子列表。这工作正常,我的帖子组件显示正确。
但是,当我向我的单数帖子添加点击功能以便它转到基于 post.id 的“FullPost”组件时,我收到一条错误消息,提示它“无法读取未定义的属性‘推送’”。当我不使用道具但对值进行硬编码时,它可以正常工作并且点击按预期工作,它会转到 FullPost 组件和基于 id 的 url。
我已尝试打印出“this.props.history”,但它确实显示“未定义”。我不知道如何定义这个以及为什么添加道具会使这个未定义。
父母这样称呼它:
<Route path="/food" exact render={() => <Posts pathname="/posts" filter="food" />} />
render() 方法似乎不包含生命钩子,所以它不包含历史?但是,如果我不在 Route 中使用 render() 而不是 component={},我不确定如何包含我的道具。
下面是代码:
import React, { Component } from 'react';
import axios from '../../../axiosPosts';
import Aux from '../../../hoc/Aux/Aux';
import classes from './Posts.css';
import Post from '../../../components/Post/Post';
class Posts extends Component {
state = {
posts: []
}
componentDidMount () {
//console.log('posts props: ', this.props.pathname, ', posts filter: ', this.props.filter, ', this props: ', this.props);
this.getData(this.props.pathname, this.props.filter);
}
getData(pathname, filter) {
axios.get(pathname + '.json')
.then(response => {
const post = response.data.filter(({category}) => category === filter);
const updatedPosts = post.map(post => {
return {
...post
}
});
this.setState({
posts: updatedPosts
});
console.log( 'history: ', this.props.history );
})
.catch(error => {
console.log(error);
});
}
postSelectedHandler = ( id ) => {
this.props.history.push( this.props.match.url + '/' + id );
}
render () {
let posts = <p style={{textAlign: 'center'}}>Whoops! Something went wrong.</p>;
if(!this.state.error) {
posts = this.state.posts.map(post => {
return (
<Post
key={post.id}
title={post.title}
dek={post.dek}
clicked={() => this.postSelectedHandler( post.id )} />
);
});
};
return (
<Aux>
<div className={classes.PostList}>
<h2 className={classes.PostListTitle}>{this.props.filter}</h2>
{posts}
</div>
</Aux>
)
}
}
export default Posts;
【问题讨论】:
标签: javascript reactjs axios prop