Lodash的反跳在React中不起作用

编程入门 行业动态 更新时间:2024-10-08 10:31:29
本文介绍了Lodash的反跳在React中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最好先看一下我的代码:

it would be best to first look at my code:

import React, { Component } from 'react'; import _ from 'lodash'; import Services from 'Services'; // Webservice calls export default class componentName extends Component { constructor(props) { super(props); this.state = { value: this.props.value || null } } onChange(value) { this.setState({ value }); // This doesn't call Services.setValue at all _.debounce(() => Services.setValue(value), 1000); } render() { return ( <div> <input onChange={(event, value) => this.onChange(value)} value={this.state.value} /> </div> ) } }

只需一个简单的输入.在构造器它抓住值从道具(如果有的话)在套的局部状态的部件.

Just a simple input. In the contructor it grabs value from the props (if available) at sets a local state for the component.

然后在 input 的 onChange 函数中,我更新状态,然后尝试调用Webservice端点以使用 Services.setValue().

Then in the onChange function of the input I update the state and then try to call the webservice endpoint to set the new value with Services.setValue().

起作用的是,如果我直接通过输入的 onChange 设置去抖,如下所示:

What does work is if I set the debounce directly by the onChange of the input like so:

<input value={this.state.value} onChange={_.debounce((event, value) => this.onChange(value), 1000)} />

但是随后 this.setState 仅每1000毫秒被调用一次并更新视图.因此,在文本字段中键入内容最终看起来很奇怪,因为您键入的内容只会在稍后显示.

But then this.setState gets called only every 1000 milliseconds and update the view. So typing in a textfield ends up looking weird since what you typed only shows a second later.

在这种情况下我该怎么办?

What do I do in a situation like this?

推荐答案

发生此问题是因为您没有调用反跳功能,您可以按以下方式进行操作

The problem occurs because you aren't calling the debounce function, you could do in the following manner

export default class componentName extends Component { constructor(props) { super(props); this.state = { value: this.props.value || null } this.servicesValue = _.debounce(this.servicesValue, 1000); } onChange(value) { this.setState({ value }); this.servicesValue(value); } servicesValue = (value) => { Services.setValue(value) } render() { return ( <div> <input onChange={(event, value) => this.onChange(value)} value={this.state.value} /> </div> ) } }

更多推荐

Lodash的反跳在React中不起作用

本文发布于:2023-11-25 11:50:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中不   Lodash   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!