Reactjs React useCallback在第一次更改时不更新状态
我正在尝试创建搜索下拉列表,但我的搜索筛选器未通过Reactjs React useCallback在第一次更改时不更新状态,reactjs,react-hooks,onchange,usecallback,Reactjs,React Hooks,Onchange,Usecallback,我正在尝试创建搜索下拉列表,但我的搜索筛选器未通过useCallback正确更新。searchFilter回调不会更新第一次更改时的值 const [inputValue, setInputValue] = useState(''); const [opts, setOpts] = useState(allOptions); const searchFilter = useCallback( (val) => { setInputValue(val);
useCallback
正确更新。searchFilter回调不会更新第一次更改时的值
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>
我的useCallback
实现有什么问题
我甚至尝试在逻辑中添加一个ref
,但没有成功。我在React文档中阅读了他们喜欢使用REF的许多输入更改:
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}
/>
const[inputValue,setInputValue]=useState(“”);
const[opts,setOpts]=useState(allOptions);
const inputEl=useRef(null);
useffect(()=>{
inputEl.current=inputValue;//将其写入ref
});
const searchFilter=useCallback(
(val)=>{
设置输入值(val);
const filter=val.toUpperCase();
常量ops=options.filter((opt)=>opt.text.toUpperCase().indexOf(filter)>-1);
setOpts(ops);
},[输入]
);
searchFilter(e.target.value)}
值={inputValue}
/>
**注意,我尝试添加一个JS代码段,但似乎我还不能将react钩子添加到stackoverflow。需要处理React版本16.8+。如果有办法,请告诉我。React可能会将多个setState()调用批处理到一个更新中以提高性能。 由于this.props和this.state可能会异步更新,因此不应依赖它们的值来计算下一个状态 例如,此代码可能无法更新计数器:
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
要修复它,请使用第二种形式的setState(),它接受函数而不是对象。该函数将接收前一个状态作为第一个参数,应用更新时的道具作为第二个参数:
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
查看关于react:State and Lifecycle(状态和生命周期)的此页,它似乎对我有用,不更新的价值是什么?输入值还是显示的选项
ah我添加了inputValue作为依赖项而不是选项!而且它似乎工作正常
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));