Reactjs 反应类型脚本对象文字错误
我有一个组件,它只呈现一行数据,并且每行都有一个删除按钮。单击delete只需使用过滤器过滤掉单击的行来更改状态。为什么我会得到下面的错误 我尝试使用console.log进行调试,确实获得了正确的row.id和rowId进行筛选,但是没有重新分配我的rows状态Reactjs 反应类型脚本对象文字错误,reactjs,typescript,Reactjs,Typescript,我有一个组件,它只呈现一行数据,并且每行都有一个删除按钮。单击delete只需使用过滤器过滤掉单击的行来更改状态。为什么我会得到下面的错误 我尝试使用console.log进行调试,确实获得了正确的row.id和rowId进行筛选,但是没有重新分配我的rows状态 interface TableSampleProps { rows: any[]; } interface TableSampleState { rows: any[]; } export class TableS
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),
};
}
}
interface TableSampleProps{
行:任何[];
}
接口表抽样{
行:任何[];
}
导出类TableSample扩展React.Component{
构造函数(props:TableSampleProps){
超级(道具);
此.state={
行:this.props.rows.concat(),
};
}
公共渲染(){
返回;
}
private deleteRow=(rowId:number)=>{
//console.log(rowId);
//this.state.rows.filter((row)=>console.log(row.id!==rowId));
this.setState={
行:this.state.rows.filter((row)=>row.id!==rowId),
};
}
}
]./src/ts/components/table-sample-tool.tsx[0](57,13)中出错:错误TS2322:
类型“{rows:any[];}”不可分配给类型“{(f:(prevState:TableSample State,props:TableSampleProps)=>
拾取,“.”[0]对象文字只能指定
类型{(f:(prevS-tate:TableSampleState,props:TableSampleProps)=>
选择“…”[0]子html网页包插件
“index.html:[0]chunk{0}index.html 542 kB[条目][0]+4隐藏模块[0]网页包:未能编译
这就是您现在设置状态的方式!
setState
是一个函数,您不分配它(因此出现错误),而是调用它,传入一个对象,指示状态中更新的属性:
this.setState({
rows: this.state.rows.filter((row) => row.id !== rowId),
});
另一件需要注意的事情是,setState
是异步的,因此访问此.state.rows
不会保证它的前一个状态。使用setState
的回调,回调的第一个参数将是前一个状态,并从回调返回一个对象,如下所示:
this.setState(prevState => ({
rows: prevState.rows.filter((row) => row.id !== rowId),
}));
这将保证您正在访问以前的状态。尝试使用
setState({rows=…
而不是setState={rows…
。您可以执行This.state={}
在构造函数中,但是setState
是一个函数。Duh!!完全忽略了我从构造函数中复制的原因。谢谢!1:您的代码语法无效2:setState
是异步的。通过此.state
在其内部访问以前的状态并不保证您获得以前的状态@user1991118