【问题标题】:How to concatenate string with JSON in react.js如何在 react.js 中将字符串与 JSON 连接起来
【发布时间】:2021-10-07 20:38:42
【问题描述】:

我是新手,我正在尝试做简单的事情。

我收到来自 BE 的 JSON 数据,如下所示:

{"data":[{"id":"12345",
"name":"Blabla",
"otherName":"3300",
"completeDate":"2021-10-01T05:00:00.000+0000",   
"status":"Active",
"location":"572957393.pdf"}]}

现在位置是文件存储在服务器上的位置,我需要将 data.location 与 URL 连接起来,所以当我渲染它时,"572957393.pdf" 我会看到这个"https://www.mypage.com/files/https572957393.pdf"

我认为最好的方法是在 fetch 类方法中使用 .map 方法,但我无法使其工作

获取语句:

fetchData(params, id){
    axios({
        url:`/admin/${this.state.radioSelect}/detail`,
        method:'get',
        params
    }).then(resp => {
        //const updated = resp.data.map(location) => This is where I am trying to use .map method
        .then(resp => {
        if(resp.data.code == '200'){ 
            this.setState({
                pageSize:this.state.pagination.pageSize,
                records:resp.data.data,
                recordsTableSpin:false,
                recordsId:id,
            })
        }
    })
}

你能帮我解决这个问题吗? 谢谢。

【问题讨论】:

    标签: javascript reactjs url fetch-api


    【解决方案1】:

    如果我正确理解了您的问题,我认为您可以执行以下操作:

    fetchData(params, id){
        axios({
            url:`/admin/${this.state.radioSelect}/detail`,
            method:'get',
            params
        }).then(resp => {
            if(resp.data.code == '200'){ 
                const updatedData = resp.data.data.map(element => ({
                    ...element, 
                    location: element.location + resp.data.location
                }))
    
                this.setState({
                    pageSize: this.state.pagination.pageSize,
                    records: updatedData,
                    recordsTableSpin: false,
                    recordsId: id
                })
            }
        })
    }
    

    【讨论】:

    • 很高兴能帮上忙!
    【解决方案2】:

    连接要在浏览器中显示文件的 URL。您可以使用两种不同的状态(一种用于文件名,一种用于 URL),以便您可以像使用模板文字一样连接它们

    ${URL}${fileName}

    URL + fineName
    

    使用 MAP 试试这个

    const temp = data.map((ele) => { 返回 { ...ele, 文件:url+fileName }; });

    【讨论】:

    • 感谢您的评论,但我需要使用 .map 或其他具有所有相同数据但更改位置的东西创建新数组。它显示在许多地方,我不想到处改变它。
    猜你喜欢
    • 2020-05-04
    • 2020-07-31
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多