如何解决关于超级props移除的警告警告会破坏代码
我学习了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,curSheetIndex } = this.state;
return (
<div className="spreadsheet-viewer">
{this.renderSheetNames(names)}
{this.renderSheetData(sheets[curSheetIndex || 0])}
</div>
);
}
}
export default WithFetching(XlxsViewer);
解决方法
我们使用super(props)来访问构造函数中的props。您没有在构造函数中使用道具,这就是eslint给出错误的原因
所以为了消除eslint和代码构建中的错误
constructor() {
this.state = this.parse();
}
使用箭头功能进行绑定
parse=()=>{
//code
}
,
一条建议,将parse()
部分移至componentDidMount()
。 constructor仅应在两种情况下使用,并且不应有任何副作用:
- 通过将一个对象分配给this.state来初始化本地状态。
- 将事件处理程序方法绑定到实例。
此外,不调用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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。