gpt4 book ai didi

reactjs - 为什么 setState(this.state) 没有触发重新渲染?

转载 作者:行者123 更新时间:2023-12-05 06:47:20 25 4
gpt4 key购买 nike

我试图让我的组件在从表中删除一个条目后重新呈现。我尝试过绑定(bind)我的函数并使用 this.forceUpdate(),但似乎没有任何效果。任何帮助将不胜感激!

这是我的组件

class Directory extends Component {
constructor() {
super();
this.state = {
tenantData: [],
searchText: "",
searchedColumn: "",
tenantInfo: {},
visible: false,
userId: null,
rerender: "",
};

// this.delTenant = this.delTenant.bind(this);
this.deleteAudit = deleteAudit.bind(this);
// this.deleteTenant = this.deleteTenant.bind(this);
// this.onDeleteClick = this.onDeleteClick.bind(this);
}

这是我组件中的删除函数

 onDeleteClick = () => {
this.setState({
...this.state,
visible: false,
});
var tenantList = this.state.tenantData;
for (var i = 0; i < tenantList.length; i++) {
if (tenantList[i].userId == this.state.userId) {
console.log(this.state.userId);
delTenant({ _id: tenantList[i]._id });
deleteTenant({ _id: this.state.userId });
this.deleteAudit({ tenantID: tenantList[i]._id }).then(() => {
this.setState(this.state); // this should rerender the component but it does not
console.log("force update");
});
break;
}
}

这是我的 AntD 组件

<Modal
title="Modal"
visible={this.state.visible}
onOk={this.onDeleteClick}
onCancel={this.hideModal}
okText="Confirm"
cancelText="Cancel"
>
<p>Are you sure you want to delete this Tenant?</p>
</Modal>

编辑:

找到解决方案 - 我的组件确实重新呈现,但我的 tenantData 状态没有改变,因为我忘记在删除条目后从数据库中获取数据。

this.deleteAudit({ tenantID: tenantList[i]._id }).then(() => {
// this.setState(this.state); // this should rerender the component but it does not
this.getTenantFunction(); // this gets the new data from database and sets the state of tenantData to the updated one
});

最佳答案

this.setState(this.state); // this should rerender the component but it does not

如果您的状态或 Prop 没有改变,React 不会重新渲染您的组件。

不知道为什么forceUpdate不行,看这个例子

import React from "react";

export default class App extends React.Component {
constructor() {
super();
this.state = {
tenantData: [],
searchText: "",
searchedColumn: "",
tenantInfo: {},
visible: false,
userId: null,
rerender: ""
};
}
onDeleteClick = () => {
console.log("click");
};
onDeleteClickForced = () => {
console.log("clickForced");
this.forceUpdate();
};

render = () => {
console.log("render");
return (
<>
<button onClick={() => this.onDeleteClick()}>Not forced</button>
<button onClick={() => this.onDeleteClickForced()}>Forced</button>
</>
);
};
}

关于reactjs - 为什么 setState(this.state) 没有触发重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67140022/

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