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

问题描述 投票:0回答:1

我有一个应用程序,当用户单击按钮时,它会加载数据集。单击另一个按钮时,将加载另一个数据集。我试图每次单击按钮时清除数据集。因此,如果单击按钮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: [] });

我想念什么?

javascript reactjs react-redux
1个回答
-1
投票

我没有看到您所在州的初始化。你有构造函数吗?

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

const handleClick = this.setState({ courthouse: [] }, this.handleClickButtonOperations());
© www.soinside.com 2019 - 2024. All rights reserved.