gpt4 book ai didi

reactjs - 关于 super(props) 删除它的 Eslint 警告会破坏代码

转载 作者:行者123 更新时间:2023-12-04 08:51:33 26 4
gpt4 key购买 nike

我学习了 React 并阅读了代码,现在我看到了这个 Eslint 警告
(props(
我这样重构代码:删除 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);

最佳答案

一个建议,移动parse()部分至componentDidMount() . constructor应该只在两种情况下使用,并且不应该有任何副作用:

  • 通过将对象分配给 this.state 来初始化本地状态。
  • 将事件处理程序方法绑定(bind)到实例。

  • 另外,不要调用 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);

    关于reactjs - 关于 super(props) 删除它的 Eslint 警告会破坏代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64076817/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com