0

我需要一些帮助。我有一个应用程序通过输入类型文件获取 *.xml 文件,并将其转换为 js 对象。为此,我从这里https://www.npmjs.com/package/xml-js使用 FileReader 和 xml-js 库

现在我有两个我无法处理的问题。

  1. xml 文件包含西里尔符号,在控制台中它们显示为 ������ ������� 在此处输入图像描述
  1. 第二个问题是,由于某些原因,我无法将转换后的对象设置为状态。

这是我的代码:文件的处理程序和输入:

handleFile = (event) => {
    let file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsText(file);
    reader.onloadend = () => {
        let json = xmljs.xml2js(reader.result, {compact: true, spaces: 4});
        this.setState({
            file: json
        }, console.log ('file', json))
    }
};

render() {

    return (
        <div>
            <input type="file" onChange={this.handleFile}/>
        </div>
    )
}

那么我应该做什么来显示西里尔符号以及如何将对象设置为状态?

4

1 回答 1

0

我修好了它。现在我的代码看起来是这样的:

handleFile = (event) => {
    let file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsText(file, 'windows-1251');
    reader.onloadend = () => {
        let json = xmljs.xml2js(reader.result, {compact: true, spaces: 4});
        this.setState({
            file: json
        }, () => {console.log('state', this.state)})
    }
};

render() {

    return (
        <div>
            <input type="file" onChange={this.handleFile}/>
        </div>
    )
}

我添加了“windows-1251”来定义编码类型,它有助于西里尔符号。我也将 setState 之后的回调函数更改为 () => {console.log('state', this.state)} 之后我可以看到当前状态,其中包含 xml 文件的内容。

于 2020-09-27T16:24:38.157 回答