【问题标题】:decodeURIComponent in ReactReact 中的 decodeURIComponent
【发布时间】:2021-11-21 18:13:15
【问题描述】:

我目前正在开发一个 react-native 应用程序,但我遇到了一个问题。我正在从 API 获取数据,数据看起来像这样

{
  "current":{
    ...
    "name": " - Kraftwerk - It's More Fun to Compute ",
    ...
  }
}  

我想解码此字符串以将其显示在我的视图中,以便将It's 转换为It's

在更新 state 之前,我尝试使用 JavaScript 函数 decodeURIComponent 对其进行解码,但不幸的是它不起作用。我的视图仍然显示It's

这是我的组件(简化)

import React, {useState, useEffect} from "react";
import { View, StyleSheet, Text, ActivityIndicator } from "react-native"

const Metadata = props => {

    const [track, setTrack] = useState({
        name: "",
        type: ""
    });
 
    const trackinfo = (data) => {
        
        let trackName = decodeURIComponent(data['current']['name']);
        let trackType = data['current']['type'];

        setTrack({
            name: trackName,
            type: trackType
        });

    useEffect(() => {
      ...
    }, []);
 
    return (
        <View style={styles.container}>
            <Text>
                {track['name']}
            </Text>
        </View>
    );
};

export default Metadata;

任何想法为什么decodeURIComponent() 无效?

谢谢

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    您可以使用html-entitites库的decode函数。

    import {decode} from 'html-entities';
    
    let trackName = decode(data['current']['name']);
    

    【讨论】:

      猜你喜欢
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多