【问题标题】:How to perform an axios get request with route parameters in the URL?如何使用 URL 中的路由参数执行 axios get 请求?
【发布时间】:2017-09-06 09:08:42
【问题描述】:

所以,我有一个动作创建器,我想从我的 API 端点获取数据。

以下作品:

export function getData(){
    return function(dispatch){
        axios.get('/api/form/myuser/mytitle').then( (res) => {
            console.log(res.data);
            return dispatch(retrieve(res.data))
        })
        .catch( (err) => {
            console.log(err)
        })
    }
}

然而,就我而言,API 端点发生了变化。 我首先对这个 URL 做一个服务器请求:/api/form/:userId/:title 然后,我真正想做的是上面的动作创建者在我的客户端有一个 axios get 请求,如下所示:

axios.get('/api/form/:userId/:title')

这里的控制台日志显然没有返回title String,而是返回:title

有可能做我想做的事吗?如果没有,还有什么建议吗?

【问题讨论】:

  • 所以您希望字符串动态格式化,因为每个请求的 url 都不相同?

标签: redux react-redux axios


【解决方案1】:

好的,我找到了答案:)

解决方案在于 react-router。在此之前,我对 react-router 还不够熟悉。

诀窍是在你的路由路径中定义你的参数,无论它在哪里(你的商店,或者你定义所有路由的文件),如下所示:

<Route path = "form/:userId/:formtitle" component = {Form} />

然后,您可以通过这样的道具在您的表单组件中访问这些参数:

this.props.params.userId 
this.props.params.formtitle

为了让您的动作创建者可以使用上述道具,您可以将它们用作您在组件中触发的动作创建者的参数,如下所示:

this.props.getData (this.props.params.userId, this.props.params.formtitle)

更多细节在这里:https://github.com/reactjs/react-router-tutorial/tree/master/lessons/08-index-routes

【讨论】:

    【解决方案2】:

    我认为模板字符串可以是解决您的问题的好方法。请不要犹豫,使用 Alt Gr + 7! :)

    axios.get(`/api/form/${userId}/${title}`)
    

    小心未定义的值。

    https://developer.mozilla.org/hu/docs/Web/JavaScript/Reference/Template_literals

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-27
      • 2022-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多