react-native - 使用 axios 使用 Rest api

标签 react-native react-redux axios

我想在 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 硬编码为:

,那么 DO 就可以工作:
url: 'books/' + '5f914f39342ba5b506cb386f',

调用我执行的操作:

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

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

getChatRoom(bookId);

我的错误在哪里?

谢谢

最佳答案

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

url: `books/${bookId}`

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

关于react-native - 使用 axios 使用 Rest api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64498431/

相关文章:

listview - React Native ListView 不会通过单击重新渲染状态更改

node.js - 从完整格式的响应触发大文件下载

vue.js - 如何从 Nuxt 商店导航到错误页面

javascript - 如何测试来自 ES6 类中定义的函数的异步 axios 调用?

javascript - VueJS 合并数据源

ios - 使用 Expo 构建二进制文件是否会压缩应用程序的大小?

javascript - firestore 数据结构的最佳实践是什么?

javascript - 如果我在 throw props 中调用函数,useEffect 会显示警告吗?

javascript - Redux:从 Web 服务访问状态的正确方法?

react-native - 在响应 native 中处理网络请求失败