簡體   English   中英

React refs 在 useCallback 中如何表現?

[英]How do React refs behave inside useCallback?

我不希望下面的 React 應用程序能正常工作,但確實如此。 我希望 useCallback 鈎子能夠捕獲並保留 ref 的初始值。 我知道 ref 無法在依賴數組中列出,所以這可能是僅用於 refs 的特殊情況?

為什么在 App 首次渲染時,useCallback 不會只捕獲一次 newTodoRef.current.value 的內容?

import React, { useCallback, useReducer, useRef } from 'react';

type Todo = { id: number, text: string }
type ActionType = { type: 'ADD', text: string} | { type: 'REMOVE', id: number}

const todoReducer = (state: Todo[], action: ActionType) => {
    switch(action.type) {
        case 'ADD': return [ ...state, { id: state.length, text: action.text }]
        case 'REMOVE': return state.filter(({ id }) => id !== action.id) // this is buggy, but that's beside the point
        default: throw new Error()
    }
}

function App() {
    const [todos, dispatch] = useReducer(todoReducer, [])

    const newTodoRef = useRef<HTMLInputElement>(null)

    const onAddTodo = useCallback(() => {
        if (newTodoRef.current) {
            dispatch({ type: "ADD", text: newTodoRef.current.value })
            newTodoRef.current.value = ''
        }
    }, [])

    return (
        <div>
            {todos.map(todo => (
                <div key={todo.id}>
                    {todo.text}
                    <button onClick={() => dispatch({ type:"REMOVE", id: todo.id })}>Remove</button>
                </div>
            ))}
            <input type="text" ref={newTodoRef}/>
            <button onClick={onAddTodo}>ADD</button>
        </div>
    )
}

export default App;

為什么在 App 首次渲染時,useCallback 不會只捕獲一次 newTodoRef.current.value 的內容?

以這種方式捕獲對頂級newTodoRef的引用 newTodoRef 。 這很好的原因是 ref 是一個可變的 object,並且每個渲染都使用相同的 object。 一旦 react 在頁面上創建了 div 元素,它將改變newTodoRef ,將其.current屬性更改為該元素。 稍后,您訪問newTodoRef ,它仍然是相同的 object,您將獲得它的.current屬性。 同時屬性發生了變化,但 object 沒有。

暫無
暫無

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

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