javascript - 在 React 中使用 Axios getData 中的道具时历史推送未定义
问题描述
我试图通过添加来自父级的道具来使这个帖子组件可重用。我的道具是“路径名”和“过滤器”。我有一个我想要更新的数据库的路径名和一个过滤器,它允许我从该数据库中过滤掉数据。它根据路径名和过滤器打印出帖子列表。这工作正常,我的帖子组件显示正确。
但是,当我将点击功能添加到我的单一帖子中以便它转到基于 post.id 的“FullPost”组件时,我收到一条错误消息,提示它“无法读取未定义的属性‘推送’”。当我不使用道具但对值进行硬编码时,它可以正常工作并且点击按预期工作,它会转到 FullPost 组件和基于 id 的 url。
我试过打印出'this.props.history',它确实显示'undefined'。我不确定如何定义它以及为什么添加道具会使它未定义。
父母这样称呼它:
<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;
解决方案
你错过了路线道具:
<Route path="/food" exact render={(routeProps) => <Posts pathname="/posts" filter="food" {...routeProps} />} />
或(如果您只需要history
):
<Route path="/food" exact render={({history}) => <Posts pathname="/posts" filter="food" history={history} />} />
推荐阅读
- python - 没有名为 loglevels 的模块
- java - 我们可以在 Amazon S3 中的单个 Java SDK 调用中执行、创建存储桶、阻止公共访问和存储桶版本控制功能吗?
- if-statement - ActionScript 3 If Else for Button Click
- asp.net - 是否所有网络托管服务提供商都支持 ASP.NET 网站?
- r - 如何使用值过滤器进行 summarise_all 与列无关
- checksum - 为什么本地 RSK 节点显示我的智能合约的“无效地址”,即使我可以在区块浏览器中看到它?
- mongodb - aws documentdb 是否为两种方式的 ssl 验证 mongodb 客户端证书?
- python - 有没有其他方法可以使用列表中的项目排除边界?
- c++ - 可以向前看的C++正则表达式?
- javascript - 使用 ng-click 加载角度 js 数据表