javascript - 在 React 中触发函数之前如何等待 setState 完成?

标签 javascript reactjs state

这是我的情况:

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

低于标准的解决方案:

  • 将 this.findRoutes() 放在 componentDidUpdate() 中
  • 这是 Not Acceptable ,因为会有更多与 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>
                );
            }
        });

最佳答案

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() 调用中, 作为第二个参数。
没有 () 因为您正在传递函数。

关于javascript - 在 React 中触发函数之前如何等待 setState 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37401635/

相关文章:

javascript - 如何使用 chart.js 为折线图绘制圆边

javascript - 我应该为大型企业应用程序使用 Material-UI 吗?

javascript - 削减使用货币转换器 Web 服务产生的结果的值(value)

javascript - React Hooks 渲染两次

reactjs - 删除重复的 sass 导入(webpack)

reactjs - 出现错误 : TypeError: Cannot read property 'getId' of undefined in React + truffle DApp

reactjs - 如果您发送 React Xstate 中不存在的事件会发生什么?

javascript - 从动态内容中获取 LI 数据 ID

reactjs - 从输入中获取数字时,React 计数器不会增加

python - 有没有办法使 tkinter Frame 变灰(禁用)?