在React中处理非同步按钮点击和防抖问题可以通过以下几种方法:
import React, { useState, useEffect } from 'react';
import { debounce } from 'lodash';
const App = () => {
const [loading, setLoading] = useState(false);
const handleClick = debounce(() => {
setLoading(true);
// 异步操作
setTimeout(() => {
setLoading(false);
}, 1000);
}, 300);
return (
<button onClick={handleClick} disabled={loading}>
{loading ? 'Loading...' : 'Click Me'}
</button>
);
};
export default App;
import React, { useReducer } from 'react';
import { debounce } from 'lodash';
const initialState = {
loading: false,
};
const reducer = (state, action) => {
switch (action.type) {
case 'SET_LOADING':
return { ...state, loading: action.payload };
default:
return state;
}
};
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const handleClick = debounce(() => {
dispatch({ type: 'SET_LOADING', payload: true });
// 异步操作
setTimeout(() => {
dispatch({ type: 'SET_LOADING', payload: false });
}, 1000);
}, 300);
return (
<button onClick={handleClick} disabled={state.loading}>
{state.loading ? 'Loading...' : 'Click Me'}
</button>
);
};
export default App;
这些方法都可以在React中处理非同步按钮点击和防抖问题,具体选择哪种方式取决于你的项目需求和个人喜好。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。