如何在axios.get函数中传递参数?

时间:2019-07-19 13:51:05

标签: reactjs typescript axios

我试图通过一个组件传递道具。它可以工作,但是我不能将值放在axios.get的URL中。 我在其他组件中有相同的代码,并且在那里工作。 希望有人能帮助我。

interface VideoProps {
    videoId: number
}

interface CommentState {
    comments: any,
    videoId: number
}

export default class ShowComments extends React.Component<VideoProps, CommentState>
{
constructor(props: CommentState) {
    super(props);

    this.state = {
        comments: [],
        videoId: this.props.videoId,
    };
}

componentWillMount(): void {
    const videoId = this.props.videoId;
    axios.get('/api/get/comments/'+ videoId)
        .then((response: any) => {
            console.log(response);
            this.setState({
                comments: response.data
            });
        });
}

1 个答案:

答案 0 :(得分:0)

    axios.get(`/api/get/comments/${videoId}`, {
      params: {
        param1: 'param1',
      }
    })
    .then((response: any) => {
        console.log(response);
        this.setState({
            comments: response.data
        });
    });

此外,这将不起作用:

this.state = {
    comments: [],
    videoId: this.props.videoId,
};

this.props应该在构造函数中未定义,请使用props.videoId,不确定是否会导致错误。