如何在React中使用onClick重置状态的特定部分



我有一个应用程序,当用户单击按钮时,它会加载数据集。单击另一个按钮时,将加载不同的数据集。每次单击按钮时,我都试图清除数据集。因此,如果我单击按钮2,按钮1的状态将重置为[](数据是数组(

这是我的代码:

class Home extends React.Component {
handleCopyTrack = (event) => {
event.preventDefault();
this.setState({ courthouse: [] });
let args = {
selected_site_id: this.props.authenticate.selected_site_id,
site_name: this.props.authenticate.site_name,
sec_organization_id: this.props.authenticate.selected_sec_organization_id,
sec_user_name: this.props.authenticate.sec_user_name,
};
this.props.loadCopyTrackInfo(args);
};
handleCourtHouse = (event) => {
event.preventDefault();
this.setState({ copytrack: [] });
let args = {
selected_site_id: this.props.authenticate.selected_site_id,
site_name: this.props.authenticate.site_name,
sec_organization_id: this.props.authenticate.selected_sec_organization_id,
sec_user_name: this.props.authenticate.sec_user_name,
};
this.props.loadCourtHouseInfo(args);
};

这部分不起作用:this.setState({ courthouse: [] })

我错过了什么?

我没有看到您的状态的初始化。你有建造师吗?

setState也是一个异步函数。如果您想更改一个状态,然后将该状态与更改的值一起使用,则必须在setState的回调中调用其他函数。

const handleClick = this.setState({ courthouse: [] }, this.handleClickButtonOperations());

以下是我解决它的方法:

我设置本地状态:

class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
showCopytrack: false,
showCourtHouse: false,
};

}

然后,当调用事件时,我更新交替状态:

handleCopyTrack = (event) => {
event.preventDefault();
this.setState({ showCopytrack: true });
this.setState({ showCourtHouse: false });

然后我根据设置为真或假来显示或隐藏:

{this.state.showCopytrack === true ? (

我建议切换到挂钩:

const Home = ({authenticate, loadCopyTrackInfo, loadCourtHouseInfo}) => {
const [courtHouse, setCourtHouse] = useState([]);
const [copyTrack, setCopyTrack] = useState([]);
function handleCopyTrack(event) {
event.preventDefault();
//Why you even need to clear this array here? Initial state will be empty array so after click new data will be added so no need to clearing
//setCourtHouse([]);
//you can pass here authenticate object
return loadCopyTrackInfo(authenticate);
};
function handleCourtHouse(event) {
event.preventDefault();
//setCopyTrack([]);
return loadCourtHouseInfo(authenticate);
};

相关内容

  • 没有找到相关文章

最新更新