简体   繁体   English

如何在Reactjs中从setstate初始化?

[英]How to initialize from setstate in Reactjs?

我仍然可以初始化setstate,但值只能从state中获取

_handleClickFilter(value, xname, chartId){
    console.log("dataSourceId", this.state.dataSource);
    this.setState({
          filterData: [{
          filter: "equals",  
          value:value ,
          attribute:xname, 
        }]
        });

    let filterdefinitions = {
        dataSourceId : "59ef50d6e4b054efd6d8aa53",
        filterDefinitions: this.state.filterData,
      }

      let data = {
        filterDefinitions: [filterdefinitions],
      };
      DashboardAction._ApplicableFilterToDashboard(data, this.props.params.dashboardId);
      DashboardAction._ApplicableFilterToChart(data, this.props.params.dashboardId, chartId);
      DashboardAction._saveFilterToDashboard(data, this.props.params.dashboardId);


}

I am able to get values in the setstate which I want. 我能够在所需的setstate中获取值。 But the values are not getting set. 但是这些值尚未设置。 Showing the values exists in the this.state only. 显示值仅存在于this.state中。

thanks in advance 提前致谢

Replace your set state code with this 以此替换您的设置状态代码

   this.setState({ 
        filterData: this.state.filterData.map((data, index) => {
        data.filter = "equals",
        data.value = value,
        data.attribute=xname
}) });

setState is async , so it's not guaranteed that the state will be set after you have used it until the re-render is triggered. setState是async ,因此不能保证在使用状态后才会设置状态,直到触发重新渲染为止。 You should be very careful about using the state right after you have set it, a more 'reactive' approach is usually better. 设置状态后,您应该非常小心使用状态,通常使用“反应性”更好的方法。 However, if you want to make sure that you'll be able to access the new state, you can use the second argument of setState which is a callback function that will be called when the state is set. 但是,如果要确保可以访问新状态,则可以使用setState第二个参数,参数是在设置状态时将调用的回调函数。

You can use it this way: 您可以通过以下方式使用它:

_handleClickFilter(value, xname, chartId){
    this.setState({
          filterData: [{
          filter: "equals",  
          value:value ,
          attribute:xname, 
        }]
    }, () => {

    let filterdefinitions = {
        dataSourceId : "59ef50d6e4b054efd6d8aa53",
        filterDefinitions: this.state.filterData,
      }

      let data = {
        filterDefinitions: [filterdefinitions],
      };
      DashboardAction._ApplicableFilterToDashboard(data, this.props.params.dashboardId);
      DashboardAction._ApplicableFilterToChart(data, this.props.params.dashboardId, chartId);
      DashboardAction._saveFilterToDashboard(data, this.props.params.dashboardId);

    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM