Reactjs 具有React输入的Lodash去抖动

Reactjs 具有React输入的Lodash去抖动,reactjs,lodash,relay,debouncing,Reactjs,Lodash,Relay,Debouncing,我正在尝试将带lodash的去Bouncing添加到搜索函数中,该函数是从InputOnChange事件调用的。下面的代码生成一个类型错误“function is expected”,我理解这一点,因为lodash需要一个函数。做这件事的正确方法是什么?它可以全部内联完成吗?到目前为止,我几乎试过了所有的例子,但都无济于事 search(e){ let str = e.target.value; debounce(this.props.relay.setVariables({ query:

我正在尝试将带lodash的去Bouncing添加到搜索函数中,该函数是从InputOnChange事件调用的。下面的代码生成一个类型错误“function is expected”,我理解这一点,因为lodash需要一个函数。做这件事的正确方法是什么?它可以全部内联完成吗?到目前为止,我几乎试过了所有的例子,但都无济于事

search(e){
 let str = e.target.value;
 debounce(this.props.relay.setVariables({ query: str }), 500);
},

这不是一个容易的问题

一方面,为了解决您遇到的错误,您需要将您的
setVariables
包装到函数中:

 search(e){
  let str = e.target.value;
  _.debounce(() => this.props.relay.setVariables({ query: str }), 500);
}

另一方面,我认为去Bouncing逻辑必须包含在继电器内部。

去Bouncing函数可以在JSX中内联传递,也可以直接设置为类方法,如下所示:

search: _.debounce(function(e) {
  console.log('Debounced Event:', e);
}, 1000)
小提琴:

如果您使用的是es2015+,您可以直接在
构造函数
中或在
componentWillMount等生命周期方法中定义去盎司方法

示例:

class DebounceSamples extends React.Component {
  constructor(props) {
    super(props);

    // Method defined in constructor, alternatively could be in another lifecycle method
    // like componentWillMount
    this.search = _.debounce(e => {
      console.log('Debounced Event:', e);
    }, 1000);
  }

  // Define the method directly in your class
  search = _.debounce((e) => {
    console.log('Debounced Event:', e);
  }, 1000)
}

这就是我在谷歌上搜索了一整天后不得不做的事情

const MyComponent = (props) => {
  const [reload, setReload] = useState(false);

  useEffect(() => {
    if(reload) { /* Call API here */ }
  }, [reload]);

  const callApi = () => { setReload(true) }; // You might be able to call API directly here, I haven't tried
  const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));

  function handleChange() { 
    debouncedCallApi(); 
  }

  return (<>
    <input onChange={handleChange} />
  </>);
}
const MyComponent=(道具)=>{
const[reload,setReload]=useState(false);
useffect(()=>{
如果(重新加载){/*在此处调用API*/}
},[reload]);
const callApi=()=>{setReload(true)};//您可以在这里直接调用API,我还没有尝试过
const[debouncedCallApi]=useState(()=>u0.debounce(callApi,1000));
函数handleChange(){
去BouncedCallAPI();
}
返回(
);
}
@Aximili

const [debouncedCallApi] = useState(() => _.debounce(callApi, 1000));
看起来很奇怪:)我准备使用
useCallback

const [searchFor, setSearchFor] = useState('');

const changeSearchFor = debounce(setSearchFor, 1000);
const handleChange = useCallback(changeSearchFor, []);

对于您的情况,应该是:

search = _.debounce((e){
 let str = e.target.value;
 this.props.relay.setVariables({ query: str });
}, 500),
save()是要调用的函数

debounceSave()是您实际调用(多次)的函数。

这对我很有用:

handleChange(event) {
  event.persist();
  const handleChangeDebounce = _.debounce((e) => {
    if (e.target.value) {
      // do something
    } 
  }, 1000);
  handleChangeDebounce(event);
}

我发现这里的许多答案过于复杂或不准确(即,实际上并没有去抖动)。下面是一个简单的解决方案,带有一个复选框:

const[count,setCount]=useState(0);//简单检查去盎司是否有效
常量handleChangeWithDebounce=u.debounce(异步(e)=>{
如果(e.target.value&&e.target.value.length>4){
//TODO:在此处进行API调用
设置计数(计数+1);
console.log('当前计数:',计数)
}
}, 1000);

使用功能性react组件,尝试使用
useCallback
useCallback
将记忆去盎司函数,以便在组件重新加载时不会一次又一次地重新创建该函数。如果没有
useCallback
,解盎司功能将不会与下一个按键笔划同步

`

从'react'导入{useCallback};
从“lodash/debounce”进口“debouce”;
从“axios”导入axios;
函数输入(){
const[value,setValue]=使用状态(“”);
const debounceFn=useCallback(_debounce(handleDebounceFn,1000),[]);
函数去Bouncefn(输入值){
axios.post(“/endpoint”{
值:输入值,
})。然后((res)=>{
console.log(res.data);
});
}
函数句柄更改(事件){
设置值(event.target.value);
debounceFn(事件、目标、值);
};
返回
}

`这是正确的FC方法 @

Aximili answers只触发一次

从“react”导入{SyntheticEvent}
导出类型WithOnChange={
onChange:(值:T)=>void
}
导出类型WithValue={
值:T
}
//WithValue&WithOnChange
导出类型VandC=WithValue和WithOnChange
export const inputValue=(e:SyntheticEvent):string=>(e.target作为HTMLElement&{value:string}).value
常量MyComponent:FC=({onChange,value})=>{
const[reload,setReload]=useState(false)
常量[状态,设置状态]=使用状态(值)
useffect(()=>{
如果(重新加载){
log('调用的api')
onChange(州)
setReload(false)
}
},[重新加载])
常量callApi=()=>{
setReload(真)
}//您可以在这里直接调用API,我还没试过
const[debouncedCallApi]=useState(()=>u.debounce(callApi,1000))
函数handleChange(x:string){
设置状态(x)
debouncedCallApi()
}
返回(
)
}

谢谢。我现在看到的是合成事件的控制台日志,我需要e.target.value来执行搜索。。我试过e.persist(),但似乎没有任何效果。从技术上讲,去抖动是可行的,但如果不传递一个值,它就不起作用。谢谢你的帮助。我不能准确地使用它,但它让我到达了我需要去的地方。我基本上进行了输入调用搜索(e),然后通过去抖动将该事件传递给另一个函数。我读过event.persist()的文章,但我没能得到那份工作。谢谢你的帮助@杰夫·伍登·菲登因建议组件安装而被解雇。能够访问道具功能,以及在去公告功能。如果我将道具放在构造函数中,不知何故我无法访问道具函数。@RajeshMbm您可以访问类构造函数中的道具,请参阅更新的示例-它作为第一个参数可用(请确保包含超级调用)。useEffect触发器只能使用一次,因为第一次调用后重新加载将始终为真。请尝试将您的值设置为handleChange,而不是debouncedCallApi,然后是callApi->state,在这个useEffect触发您的函数后^ ^我认为它调用了n次,只是应用了延迟,次,我至少现在尝试了。最好解释一下您的答案,它在做什么,如何解决OP的问题,根据需要提供一些参考资料。仅仅添加代码块或链接是不够的。试试这个
handleChange(event) {
  event.persist();
  const handleChangeDebounce = _.debounce((e) => {
    if (e.target.value) {
      // do something
    } 
  }, 1000);
  handleChangeDebounce(event);
}
    const delayedHandleChange = debounce(eventData => someApiFunction(eventData), 500);

const handleChange = (e) => {
        let eventData = { id: e.id, target: e.target };
        delayedHandleChange(eventData);
    }
import {useCallback} from 'react';
import _debouce from 'lodash/debounce';
import axios from 'axios';

function Input() {
    const [value, setValue] = useState('');

    const debounceFn = useCallback(_debounce(handleDebounceFn, 1000), []);

    function debounceFn(inputValue) {
        axios.post('/endpoint', {
          value: inputValue,
        }).then((res) => {
          console.log(res.data);
        });
    }


    function handleChange (event) {
        setValue(event.target.value);
        debounceFn(event.target.value);
    };

    return <input value={value} onChange={handleChange} />
}