我想将对象转换为reactjs(已解决)中的整型

问题描述 投票:0回答:1

我想将一个对象转换为整数并将其传递给url,但是在进行转换之后,它将转换为NAN。

export const fetchById= (id) =>dispatch =>{
    //id: object
    const d= id.toString(); //string
    const i= parseInt(d,10); //number
    console.log(typeof id); //number
    fetch(`https://cors-anywhere.herokuapp.com/https://api.nasa.gov/neo/rest/v1/neo?asteroid_id=${i}&api_key=demo_key`)
    .then(res => res.json())
        .then(data =>{
            // const d= {...data.near_earth_objects};
            return dispatch({
                type: actions.fetchByIds, data: data
            });
        });
javascript reactjs
1个回答
0
投票

无需将整个对象转换为字符串。因为字符串化对象将返回类似于JSON.stringify()的结果,并且类似于"{key: val}"

要实现当前任务,您可以直接将变量解析为整数,但是请确保将其作为整数而不是浮点数。

因此,如果这样编写,您的代码可能会起作用:

 export const fetchById= (id) =>dispatch =>{
     //id: object
     const i= parseInt(id.id); //number
     console.log(typeof id); //number
     fetch(`https://cors-anywhere.herokuapp.com/https://api.nasa.gov/neo/rest/v1/neo?asteroid_id=${i}&api_key=demo_key`)
     .then(res => res.json())
     .then(data =>{
        // const d= {...data.near_earth_objects};
        return dispatch({
            type: actions.fetchByIds, data: data
        });
    });

顺便说一句,没有必要将其转换为int,因为您所做的全部是在查询中使用它,并且查询将转换为字符串,如果您在服务器中记录asteroid_id的类型,它将是字符串。

© www.soinside.com 2019 - 2024. All rights reserved.