【发布时间】:2020-04-07 16:03:13
【问题描述】:
我正在尝试创建一个搜索下拉列表,但我的搜索过滤器没有使用useCallback 正确更新。 searchFilter 回调不会更新第一个 onChange 上的值
const [inputValue, setInputValue] = useState('');
const [opts, setOpts] = useState(allOptions);
const searchFilter = useCallback(
(val) => {
setInputValue(val);
const filter = val.toUpperCase();
const ops = options.filter((opt) => opt.text.toUpperCase().indexOf(filter) > -1);
setOpts(ops);
}, [inputValue] // state not being updated on first onChange
);
<textArea
onChange={(e) => searchFilter(e.target.value)}
value={inputValue}
/>
<ul>
{opts.map((option) => (
<li key={option.key}>
{option.text}
</li>
))}
</ul>
我能够通过取消回调来修复这个错误:
const searchFilter = (val) => {
setInputValue(val);
const filter = val.toUpperCase();
const ops = options.filter((opt) => opt.text.toUpperCase().indexOf(filter) > -1);
setOpts(ops);
} // this works on every onChange
我对@987654325@ 的实现有什么问题?
我什至尝试将ref 添加到逻辑中,但这不起作用。我在 React 文档中阅读了他们喜欢使用 refs 进行的许多输入更改:
const [inputValue, setInputValue] = useState('');
const [opts, setOpts] = useState(allOptions);
const inputEl = useRef(null);
useEffect(() => {
inputEl.current = inputValue; // Write it to the ref
});
const searchFilter = useCallback(
(val) => {
setInputValue(val);
const filter = val.toUpperCase();
const ops = options.filter((opt) => opt.text.toUpperCase().indexOf(filter) > -1);
setOpts(ops);
}, [inputEl]
);
<textArea
ref={inputEl}
onChange={(e) => searchFilter(e.target.value)}
value={inputValue}
/>
** 注意我尝试添加一个 JS sn-p 但似乎我还不能将反应钩子添加到 stackoverflow。需要处理 React 16.8+ 版本。如果有办法,请告诉我。
【问题讨论】:
标签: reactjs react-hooks onchange usecallback