【问题标题】:Consuming rest api with axios使用 axios 使用 rest api
【发布时间】:2020-10-23 10:37:34
【问题描述】:

我想在 react native 中使用带有 axios 的 rest api。我想得到一个特定的项目,所以 URL 如下 /book/637777378 如何用 axios 传递那个数字 id。

到目前为止我做了什么:

import axios from 'axios';
import config from '../Config'

const requestHelper = axios.create({
    baseURL: config.prodBaseUrl,
});

export default {
    books: {
        getAll: () => requestHelper({
            url: 'books',
            method: 'get',
        }),
        getOne: bookId => requestHelper({
            url: 'books/' + bookId, // '5f914f39342ba5b506cb386f',
            method: 'get',
        }),
        create: data => requestHelper({
            url: 'books',
            method: 'post',
            data,
        }),
    },
};

代码原样不起作用。但是,如果我将图书 ID 硬编码为:

url: 'books/' + '5f914f39342ba5b506cb386f',

调用我执行的操作:

const bookId = this.props.navigation.getParam('bookId')

console.log(bookId);   // The bookId is NOT NULL. Is CORRECT!

getChatRoom(bookId);

我的错误在哪里?

谢谢

【问题讨论】:

    标签: react-native react-redux axios


    【解决方案1】:

    使用反引号而不是单引号更改 URL,如下所示

    url: `books/${bookId}`
    

    bookId 是变量。要在字符串中添加变量,您必须使用反引号并将变量放入 ${variable_name}

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 2020-12-26
      • 2021-03-13
      • 2021-02-12
      • 2020-12-29
      • 2019-02-15
      • 2021-12-09
      • 1970-01-01
      相关资源
      最近更新 更多