在 React 中触发函数之前,我该如何等待 setState 完成?

2022-08-30 02:30:37

这是我的情况:

  • on this.handleFormSubmit() 我正在执行 this.setState()
  • inside.handleFormSubmit(), 我称之为 this.findRoutes();- 这取决于 this.setState() 的成功完成
  • this.setState();在此之前未完成。findRoutes 称为...
  • 在调用 this.findRoutes() 之前,我如何等待 this.setState() 在 this.handleFormSubmit() 中完成?

低于标准的解决方案:

  • put this.findRoutes() in 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>
                );
            }
        });

答案 1

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
);

请注意,对 的调用现在位于调用内部,作为第二个参数。
没有,因为您正在传递函数。findRoutessetState()()


答案 2

如果有人在这里着陆并且使用钩子有相同的情况,可以通过以下过程实现相同的行为

const [data, setData] = useState(false);

useEffect(() => {
    doSomething(); // This is be executed when the state changes
}, [data]);

setData(true);

这里将在数据的任何更改后运行,我们可以执行任何依赖任务。useEffect