【问题标题】:React Typescript object literal error反应打字稿对象文字错误
【发布时间】:2018-01-22 23:26:45
【问题描述】:

我有一个组件,它简单地呈现一行数据,并且每一行都有一个删除按钮。单击删除应该只是使用过滤器更改状态以过滤掉单击的行。为什么会出现以下错误。

我尝试使用 console.log 进行调试,我确实得到了正确的 row.id 和 rowId 来过滤,但我的行状态没有被重新分配。

interface TableSampleProps {
    rows: any[];
}

interface TableSampleState {
    rows: any[];
}

export class TableSample extends React.Component<TableSampleProps, TableSampleState> {
    constructor(props: TableSampleProps) {
        super(props);

        this.state = {
           rows: this.props.rows.concat(),
        };
    }

    public render() {
        return <MyTable rows={this.state.rows} onDeleteRow={this.deleteRow} />;
    }

    private deleteRow = (rowId: number) => {
        // console.log(rowId);
        // this.state.rows.filter((row) => console.log(row.id !== rowId));
        this.setState = {
            rows: this.state.rows.filter((row) => row.id !== rowId),
         };
    }
}

] ./src/ts/components/table-sample-tool.tsx [0] (57,13) 中的错误:错误 TS2322: 输入'{行:任何[]; }' 不可分配给类型 '{ (f: (prevState: TableSample State, props: TableSampleProps) => 挑选, ...'。 [0] 对象字面量只能指定 已知属性,并且 'rows' 不存在于类型 '{ (f: (prevS tate: TableSampleState, props: TableSampleProps) => 挑选, ...'。 [0] 子 html-webpack-plugin 用于 "index.html": [0] 块 {0} index.html 542 kB [entry] [0]
+ 4 个隐藏模块 [0] webpack:编译失败。

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    这就是你现在设置状态的方式! setState 是一个函数,你不分配它(因此错误),你调用它,传入一个表示状态更新属性的对象:

    this.setState({
        rows: this.state.rows.filter((row) => row.id !== rowId),
    });
    

    另外需要注意的是setState 是异步的,所以在其中访问this.state.rows 并不能保证之前的状态。为setState 使用回调,回调的第一个参数将是之前的状态,并从回调中返回一个对象,如下所示:

    this.setState(prevState => ({
        rows: prevState.rows.filter((row) => row.id !== rowId),
    }));
    

    这将保证您访问的是以前的状态。

    【讨论】:

      【解决方案2】:

      尝试使用setState({rows=... 而不是setState = {rows...。你可以在构造函数中使用this.state = {},但setState 是一个函数。

      【讨论】:

      • 呃!!完全忽略了我从构造函数中复制的原因。谢谢!
      • 1:您的代码语法无效 2:setState 是异步的。通过其中的this.state 访问先前的状态并不能保证您获得先前的状态@user1991118
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2022-01-26
      • 1970-01-01
      • 2023-04-01
      • 2022-11-10
      • 2023-01-03
      相关资源
      最近更新 更多