我学习了React并阅读了代码,现在我看到了这个Eslint警告
我这样重构代码:删除props
constructor() {
super();
this.state = this.parse();
}
现在Eslint很高兴,但是由于props
中可能无法使用this.parse();
这应该如何工作?
完整代码:
// Copyright (c) 2017 PlanGrid, Inc.
import React, { Component } from 'react';
import XLSX from 'xlsx';
import CsvViewer from './csv-viewer';
import WithFetching from '../file-viewer/fetch-wrapper';
class XlxsViewer extends Component {
constructor(props) {
super(props);
this.state = this.parse();
}
parse() {
const { data } = this.props;
const dataArr = new Uint8Array(data);
const arr = [];
for (let i = 0; i !== dataArr.length; i += 1) {
arr.push(String.fromCharCode(dataArr[i]));
}
const workbook = XLSX.read(arr.join(''), { type: 'binary' });
const names = Object.keys(workbook.Sheets);
const sheets = names.map(name => XLSX.utils.sheet_to_csv(workbook.Sheets[name]));
return { sheets, names, curSheetIndex: 0 };
}
renderSheetNames(names) {
const sheets = names.map((name, index) => (
<input
key={name}
type="button"
value={name}
onClick={() => {
this.setState({ curSheetIndex: index });
}}
/>
));
return <div className="sheet-names">{sheets}</div>;
}
renderSheetData(sheet) {
const csvProps = { ...this.props, data: sheet };
return <CsvViewer {...csvProps} />;
}
render() {
const { sheets, names, curSheetIndex } = this.state;
return (
<div className="spreadsheet-viewer">
{this.renderSheetNames(names)}
{this.renderSheetData(sheets[curSheetIndex || 0])}
</div>
);
}
}
export default WithFetching(XlxsViewer);
答案 0 :(得分:1)
我们使用super(props)来访问构造函数中的props。您没有在构造函数中使用道具,这就是eslint给出错误的原因
所以为了消除eslint和代码构建中的错误
constructor() {
this.state = this.parse();
}
使用箭头功能进行绑定
parse=()=>{
//code
}
答案 1 :(得分:1)
一条建议,将parse()
部分移至componentDidMount()
。 constructor仅应在两种情况下使用,并且不应有任何副作用:
此外,不调用super(props)
会导致您无法在this.props
中包含实际值,因为它将是undefined
。
使用this.setState()重构此代码的方式如下:
import React, { Component } from "react";
import XLSX from "xlsx";
import CsvViewer from "./csv-viewer";
import WithFetching from "../file-viewer/fetch-wrapper";
class XlxsViewer extends Component {
componentDidMount() {
this.parse();
}
parse() {
const { data } = this.props;
const dataArr = new Uint8Array(data);
const arr = [];
for (let i = 0; i !== dataArr.length; i += 1) {
arr.push(String.fromCharCode(dataArr[i]));
}
const workbook = XLSX.read(arr.join(""), { type: "binary" });
const names = Object.keys(workbook.Sheets);
const sheets = names.map((name) =>
XLSX.utils.sheet_to_csv(workbook.Sheets[name])
);
this.setState({ sheets, names, curSheetIndex: 0 });
}
...
}
export default WithFetching(XlxsViewer);