React.js,等待的setState到触发功能前完成?

问题描述 投票:69回答:3

这里是我的情况:

  • 在this.handleFormSubmit()我执行this.setState()
  • 里面this.handleFormSubmit(),我打电话this.findRoutes(); - 这取决于this.setState成功完成()
  • this.setState();未完成被称为this.findRoutes之前...
  • 如何调用this.findRoutes()之前等待this.setState()内的this.handleFormSubmit()来完成?

欠佳的解决方案:

  • 把this.findRoutes()在componentDidUpdate()
  • 这是不能接受的,因为将会有更多的状态的变化无关的findRoutes()函数。当无关的状态更新我不想触发findRoutes()函数。

请参考下面的代码片段:

handleFormSubmit: function(input){
                // Form Input
                this.setState({
                    originId: input.originId,
                    destinationId: input.destinationId,
                    radius: input.radius,
                    search: input.search
                })
                this.findRoutes();
            },
            handleMapRender: function(map){
                // Intialized Google Map
                directionsDisplay = new google.maps.DirectionsRenderer();
                directionsService = new google.maps.DirectionsService();
                this.setState({map: map});
                placesService = new google.maps.places.PlacesService(map);
                directionsDisplay.setMap(map);
            },
            findRoutes: function(){
                var me = this;
                if (!this.state.originId || !this.state.destinationId) {
                    alert("findRoutes!");
                    return;
                }
                var p1 = new Promise(function(resolve, reject) {
                    directionsService.route({
                        origin: {'placeId': me.state.originId},
                        destination: {'placeId': me.state.destinationId},
                        travelMode: me.state.travelMode
                    }, function(response, status){
                        if (status === google.maps.DirectionsStatus.OK) {
                            // me.response = response;
                            directionsDisplay.setDirections(response);
                            resolve(response);
                        } else {
                            window.alert('Directions config failed due to ' + status);
                        }
                    });
                });
                return p1
            },
            render: function() {
                return (
                    <div className="MapControl">
                        <h1>Search</h1>
                        <MapForm
                            onFormSubmit={this.handleFormSubmit}
                            map={this.state.map}/>
                        <GMap
                            setMapState={this.handleMapRender}
                            originId= {this.state.originId}
                            destinationId= {this.state.destinationId}
                            radius= {this.state.radius}
                            search= {this.state.search}/>
                    </div>
                );
            }
        });
javascript reactjs state
3个回答
201
投票

setState()具有您可以使用此可选的回调参数。你只需要稍微改变你的代码,这样的:

// Form Input
this.setState(
  {
    originId: input.originId,
    destinationId: input.destinationId,
    radius: input.radius,
    search: input.search
  },
  this.findRoutes         // here is where you put the callback
);

注意调用findRoutes现在是setState()电话里,作为第二个参数。 没有()因为要传递的功能。


12
投票
       this.setState(
        {
            originId: input.originId,
            destinationId: input.destinationId,
            radius: input.radius,
            search: input.search
        },
        function() { console.log("setState completed", this.state) }
       )

这可能是有益的


8
投票

setState()的文件的新状况可能不会体现在回调函数findRoutes()。下面是从React docs提取物:

的setState()不会立即发生变异this.state而造成挂起状态转变。调用此方法后访问this.state有可能返回现有值。

有没有电话的同步运行,保证SETSTATE,呼叫可能会分批进行性能提升。

因此,这里是我的建议,你应该做的。您应通过新的状态在回调函数input findRoutes()

handleFormSubmit: function(input){
    // Form Input
    this.setState({
        originId: input.originId,
        destinationId: input.destinationId,
        radius: input.radius,
        search: input.search
    });
    this.findRoutes(input);    // Pass the input here
}

findRoutes()功能应该被定义是这样的:

findRoutes: function(me = this.state) {    // This will accept the input if passed otherwise use this.state
    if (!me.originId || !me.destinationId) {
        alert("findRoutes!");
        return;
    }
    var p1 = new Promise(function(resolve, reject) {
        directionsService.route({
            origin: {'placeId': me.originId},
            destination: {'placeId': me.destinationId},
            travelMode: me.travelMode
        }, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                // me.response = response;
                directionsDisplay.setDirections(response);
                resolve(response);
            } else {
                window.alert('Directions config failed due to ' + status);
            }
        });
    });
    return p1
}
© www.soinside.com 2019 - 2024. All rights reserved.