React - 让XLSX进入状态?

时间:2018-05-18 01:52:58

标签: javascript reactjs xlsx

从我的React App,我尝试实现导入/导出excel。 导入功能没问题,但我怎样才能将结果送到状态?

我尝试在XLSX中使用this.setState()但语法错误。 但如果我使用 - > const data = XLSX ....,未定义数据变量。

请参阅以下导入成功的代码,但不知道如何进入该状态,请帮助验证。

handleUpload(e) {
    e.preventDefault();
    const file = e.target.files[0];
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;

        reader.onload = (e) => {
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, {type:rABS ? 'binary' : 'array'});
            const wsname = wb.SheetNames[0];
            const ws = wb.Sheets[wsname];
            // const data = XLSX.utils.sheet_to_json(ws); -> this work but cannot edit each row
            XLSX.utils.sheet_to_json(ws).forEach(r => {
                r.itemid = r.itemid.trim(),
                !r.barcode ? r.barcode = "" : r.barcode = r.barcode.trim(),
                r.itemname = r.itemname.trim(),
                r.category = r.category.trim(),
                !r.stocktype ? r.stocktype = "" : r.stocktype = r.stocktype.trim(),
                !r.itemtype ? r.itemtype = "" : r.itemtype = r.itemtype.trim(),
                r.wholesaleprice = Number(r.wholesaleprice),
                r.retailprice = Number(r.retailprice),
                !r.quantitystock ? r.quantitystock = 0 : r.quantitystock = Number(r.quantitystock),
                !r.receivingquantity ? r.receivingquantity = 0 : r.receivingquantity = Number(r.receivingquantity),
                !r.reorderlevel ? r.reorderlevel = 0 : r.reorderlevel = Number(r.reorderlevel),
                !r.description ? r.description = "" : r.description = r.description.trim(),
                !r.comment ? r.comment = "" : r.comment = r.comment.trim(),
                this.createItem(r)
                // this.createItem(r), -> syntax error
                // this.setState({ data: r }) -> syntax error
            });
            //this.setState({ data: data });  
            //console.log(this.state.data);

        };
        if (rABS) reader.readAsBinaryString(file); else reader.readAsArrayBuffer(file);
    }

0 个答案:

没有答案