簡體   English   中英

在第一次更改時反應 useCallback 不更新 state onChange

[英]React useCallback not updating state onChange on the first change

我正在嘗試創建一個搜索下拉列表,但我的搜索過濾器沒有使用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

我的useCallback實現有什么問題?

我什至嘗試在邏輯中添加一個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 片段,但似乎我還不能將反應鈎子添加到 stackoverflow。 需要處理 React 16.8+ 版本。 如果有辦法我可以做到,請告訴我。

它似乎對我有用,不更新的價值是什么? 輸入值還是顯示的選項?

https://codesandbox.io/s/brave-mcnulty-pysjj

React 可以將多個 setState() 調用批處理到單個更新中以提高性能。 因為 this.props 和 this.state 可能會異步更新,所以您不應依賴它們的值來計算下一個 state。

例如,此代碼可能無法更新計數器:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

要修復它,請使用第二種形式的 setState(),它接受 function 而不是 object。 function 將接收之前的 state 作為第一個參數,並且在應用更新時的道具作為第二個參數:

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

檢查此頁面關於反應:State 和生命周期State 更新可能是異步的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM