首页 > 解决方案 > 在 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;

标签: javascriptreactjsaxiosprop

解决方案


你错过了路线道具

<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} />} />

推荐阅读