使用钩子在 React 中去抖动/限制回调,而无需等待用户停止输入以获取更新
Debouncing / throttling a callback in React using hooks without waiting for the user to stop typing to get the update
我正在使用 React 16.8.6
与 Hooks 和 Formik 1.5.7
来构建一个表单,其中包含稍后将使用该数据生成的内容的预览。表单本身运行良好,但只要我也渲染预览,一切都会变得有点缓慢。
我已经修复了使用 setTimeout
对表单的 onChange
去抖动的问题,但我希望即使用户不断输入也能定期调用它:
const Preview = ({ values: { name = '', message = '' } }) => (<div className="preview">
<p><strong>{ name }</strong></p>
{ message.split(/\r?\n\r?\n/g).filter(Boolean).map((text, i) => (<p key={ i }>{ text }</p>)) }
</div>);
const Form = ({ onChange }) => {
const [values, setValues] = React.useState({});
// Let's assume this is internal code from Formik...:
const handleChange = React.useCallback(({ target }) => {
setValues(values => {
const nextValues = ({ ...values, [target.name]: target.value });
onChange(nextValues);
return nextValues;
});
}, []);
return (<form>
<input type="text" value={ values.name || '' } name="name" onChange={ handleChange } />
<textarea value={ values.message || '' } name="message" onChange={ handleChange } />
</form>);
};
const App = () => {
const [formValues, setFormValues] = React.useState({});
const timeoutRef = React.useRef();
React.useEffect(() => window.clearTimeout(timeoutRef.current), []);
const handleFormChange = React.useCallback((values) => {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => setFormValues(values), 500);
}, []);
return (<div className="editor">
<Form onChange={ handleFormChange } />
<Preview values={ formValues } />
</div>);
};
ReactDOM.render(<App />, document.querySelector('#app'));
body {
margin: 0;
}
body,
input,
textarea {
font-family: monospace;
}
.editor {
display: flex;
}
form,
.preview {
position: relative;
max-width: 480px;
width: 100%;
margin: 0 auto;
padding: 8px;
}
input,
textarea {
border: 2px solid black;
border-radius: 2px;
display: flex;
padding: 8px;
margin: 0 auto 8px;
width: 100%;
box-sizing: border-box;
}
.preview {
border-left: 2px solid black;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
您可以定义一个自定义 withThrottledCallback
钩子来处理这个问题,replaces/combines 这些行:
const timeoutRef = React.useRef();
React.useEffect(() => window.clearTimeout(timeoutRef.current), []);
const handleFormChange = React.useCallback((values) => {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => setFormValues(values), 500);
}, []);
变成这样的东西:
const throttledHandleFormChange = useThrottledCallback((values) => {
setFormValues(values);
}, 500, []);
即使用户不断输入,它也会每 500 毫秒定期触发。
这样,您将能够以声明方式重用此功能,而不是直接使用 setTimeout
,就像 Dan Abramov 在 Making setInterval Declarative with React Hooks.[=25= 中为 setInterval
建议的那样]
它将看起来像这样:
function useThrottledCallback(callback, delay, deps) {
const timeoutRef = React.useRef();
const callbackRef = React.useRef(callback);
const lastCalledRef = React.useRef(0);
// Remember the latest callback:
//
// Without this, if you change the callback, when setTimeout kicks in, it
// will still call your old callback.
//
// If you add `callback` to useCallback's deps, it will also update, but it
// might be called twice if the timeout had already been set.
React.useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Clear timeout if the components is unmounted or the delay changes:
React.useEffect(() => window.clearTimeout(timeoutRef.current), [delay]);
return React.useCallback((...args) => {
// Clear previous timer:
window.clearTimeout(timeoutRef.current);
function invoke() {
callbackRef.current(...args);
lastCalledRef.current = Date.now();
}
// Calculate elapsed time:
const elapsed = Date.now() - lastCalledRef.current;
if (elapsed >= delay) {
// If already waited enough, call callback:
invoke();
} else {
// Otherwise, we need to wait a bit more:
timeoutRef.current = window.setTimeout(invoke, delay - elapsed);
}
}, deps);
}
const Preview = ({ values: { name = '', message = '' } }) => (<div className="preview">
<p><strong>{ name }</strong></p>
{ message.split(/\r?\n\r?\n/g).filter(Boolean).map((text, i) => (<p key={ i }>{ text }</p>)) }
</div>);
const Form = ({ onChange }) => {
const [values, setValues] = React.useState({});
// Let's assume this is internal code from Formik...:
const handleChange = React.useCallback(({ target }) => {
setValues(values => {
const nextValues = ({ ...values, [target.name]: target.value });
onChange(nextValues);
return nextValues;
});
}, []);
return (<form>
<input type="text" value={ values.name || '' } name="name" onChange={ handleChange } />
<textarea value={ values.message || '' } name="message" onChange={ handleChange } />
</form>);
};
const App = () => {
const [formValues, setFormValues] = React.useState({});
const throttledHandleFormChange = useThrottledCallback((values) => {
setFormValues(values);
}, 500, []);
return (<div className="editor">
<Form onChange={ throttledHandleFormChange } />
<Preview values={ formValues } />
</div>);
};
ReactDOM.render(<App />, document.querySelector('#app'));
body {
margin: 0;
}
body,
input,
textarea {
font-family: monospace;
}
.editor {
display: flex;
}
form,
.preview {
position: relative;
max-width: 480px;
width: 100%;
margin: 0 auto;
padding: 8px;
}
input,
textarea {
border: 2px solid black;
border-radius: 2px;
display: flex;
padding: 8px;
margin: 0 auto 8px;
width: 100%;
box-sizing: border-box;
}
textarea {
resize: vertical;
}
.preview {
border-left: 2px solid black;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
您还可以找到 setTimeout
和 setInterval
、useTimeout
和 useInterval
的声明版本,以及一个用 TypeScript 编写的自定义 useThrottledCallback
挂钩 https://www.npmjs.com/package/@swyg/corre.
我正在使用 React 16.8.6
与 Hooks 和 Formik 1.5.7
来构建一个表单,其中包含稍后将使用该数据生成的内容的预览。表单本身运行良好,但只要我也渲染预览,一切都会变得有点缓慢。
我已经修复了使用 setTimeout
对表单的 onChange
去抖动的问题,但我希望即使用户不断输入也能定期调用它:
const Preview = ({ values: { name = '', message = '' } }) => (<div className="preview">
<p><strong>{ name }</strong></p>
{ message.split(/\r?\n\r?\n/g).filter(Boolean).map((text, i) => (<p key={ i }>{ text }</p>)) }
</div>);
const Form = ({ onChange }) => {
const [values, setValues] = React.useState({});
// Let's assume this is internal code from Formik...:
const handleChange = React.useCallback(({ target }) => {
setValues(values => {
const nextValues = ({ ...values, [target.name]: target.value });
onChange(nextValues);
return nextValues;
});
}, []);
return (<form>
<input type="text" value={ values.name || '' } name="name" onChange={ handleChange } />
<textarea value={ values.message || '' } name="message" onChange={ handleChange } />
</form>);
};
const App = () => {
const [formValues, setFormValues] = React.useState({});
const timeoutRef = React.useRef();
React.useEffect(() => window.clearTimeout(timeoutRef.current), []);
const handleFormChange = React.useCallback((values) => {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => setFormValues(values), 500);
}, []);
return (<div className="editor">
<Form onChange={ handleFormChange } />
<Preview values={ formValues } />
</div>);
};
ReactDOM.render(<App />, document.querySelector('#app'));
body {
margin: 0;
}
body,
input,
textarea {
font-family: monospace;
}
.editor {
display: flex;
}
form,
.preview {
position: relative;
max-width: 480px;
width: 100%;
margin: 0 auto;
padding: 8px;
}
input,
textarea {
border: 2px solid black;
border-radius: 2px;
display: flex;
padding: 8px;
margin: 0 auto 8px;
width: 100%;
box-sizing: border-box;
}
.preview {
border-left: 2px solid black;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
您可以定义一个自定义 withThrottledCallback
钩子来处理这个问题,replaces/combines 这些行:
const timeoutRef = React.useRef();
React.useEffect(() => window.clearTimeout(timeoutRef.current), []);
const handleFormChange = React.useCallback((values) => {
window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => setFormValues(values), 500);
}, []);
变成这样的东西:
const throttledHandleFormChange = useThrottledCallback((values) => {
setFormValues(values);
}, 500, []);
即使用户不断输入,它也会每 500 毫秒定期触发。
这样,您将能够以声明方式重用此功能,而不是直接使用 setTimeout
,就像 Dan Abramov 在 Making setInterval Declarative with React Hooks.[=25= 中为 setInterval
建议的那样]
它将看起来像这样:
function useThrottledCallback(callback, delay, deps) {
const timeoutRef = React.useRef();
const callbackRef = React.useRef(callback);
const lastCalledRef = React.useRef(0);
// Remember the latest callback:
//
// Without this, if you change the callback, when setTimeout kicks in, it
// will still call your old callback.
//
// If you add `callback` to useCallback's deps, it will also update, but it
// might be called twice if the timeout had already been set.
React.useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// Clear timeout if the components is unmounted or the delay changes:
React.useEffect(() => window.clearTimeout(timeoutRef.current), [delay]);
return React.useCallback((...args) => {
// Clear previous timer:
window.clearTimeout(timeoutRef.current);
function invoke() {
callbackRef.current(...args);
lastCalledRef.current = Date.now();
}
// Calculate elapsed time:
const elapsed = Date.now() - lastCalledRef.current;
if (elapsed >= delay) {
// If already waited enough, call callback:
invoke();
} else {
// Otherwise, we need to wait a bit more:
timeoutRef.current = window.setTimeout(invoke, delay - elapsed);
}
}, deps);
}
const Preview = ({ values: { name = '', message = '' } }) => (<div className="preview">
<p><strong>{ name }</strong></p>
{ message.split(/\r?\n\r?\n/g).filter(Boolean).map((text, i) => (<p key={ i }>{ text }</p>)) }
</div>);
const Form = ({ onChange }) => {
const [values, setValues] = React.useState({});
// Let's assume this is internal code from Formik...:
const handleChange = React.useCallback(({ target }) => {
setValues(values => {
const nextValues = ({ ...values, [target.name]: target.value });
onChange(nextValues);
return nextValues;
});
}, []);
return (<form>
<input type="text" value={ values.name || '' } name="name" onChange={ handleChange } />
<textarea value={ values.message || '' } name="message" onChange={ handleChange } />
</form>);
};
const App = () => {
const [formValues, setFormValues] = React.useState({});
const throttledHandleFormChange = useThrottledCallback((values) => {
setFormValues(values);
}, 500, []);
return (<div className="editor">
<Form onChange={ throttledHandleFormChange } />
<Preview values={ formValues } />
</div>);
};
ReactDOM.render(<App />, document.querySelector('#app'));
body {
margin: 0;
}
body,
input,
textarea {
font-family: monospace;
}
.editor {
display: flex;
}
form,
.preview {
position: relative;
max-width: 480px;
width: 100%;
margin: 0 auto;
padding: 8px;
}
input,
textarea {
border: 2px solid black;
border-radius: 2px;
display: flex;
padding: 8px;
margin: 0 auto 8px;
width: 100%;
box-sizing: border-box;
}
textarea {
resize: vertical;
}
.preview {
border-left: 2px solid black;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
您还可以找到 setTimeout
和 setInterval
、useTimeout
和 useInterval
的声明版本,以及一个用 TypeScript 编写的自定义 useThrottledCallback
挂钩 https://www.npmjs.com/package/@swyg/corre.