簡體   English   中英

`React.useState` 返回的 setState function 中的不同 function 簽名如何區分?

[英]How are different function signatures differentiated in setState function returned by `React.useState`?

我是 JavaScript 和 React 的新手。

我正在閱讀 React 的文檔https://reactjs.org/docs/hooks-reference.html#functional-updates

function Counter({initialCount}) {
  const [count, setCount] = useState(initialCount);
  return (
    <>
      Count: {count}
      <button onClick={() => setCount(initialCount)}>Reset</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
    </>
  );
}

並且很好奇 React.useState 返回的 setState (此處setCount ) function 中如何處理不同的React.useState簽名。

Since JavaScript is a dynamically typed language and therefore function overloading does not exist, my initial guess was that there's only a single function that simulates the behavior of function overloading, such as in this question Function overloading in Javascript - Best practices .

或者這是否由 React 以不同的方式處理?

編輯:我認為這個問題也可以應用於React.useState function 本身https://reactjs.org/docs/hooks-reference.html#lazy-initial-state

const [state, setState] = useState(() => {
  const initialState = someExpensiveComputation(props);
  return initialState;
});

我最初的猜測是只有一個 function 可以模擬 function 重載的行為

是的,在 javascript 中,如果您希望 function 采用各種不同的參數,您可以編寫單個 function,然后編寫檢查傳入的代碼。例如:

const example = (val) => {
  if (typeof val === 'function') {
    // do the function behavior
  } else {
    // do the other behavior
  }
}

編輯:既然你想知道反應具體使用的代碼,那就去吧。 簡而言之,它和我剛才回答的一樣,但需要更多步驟才能到達那里。

探索代碼的起點就是這個文件 這是您在調用 useState 時調用的useState 然而,它所做的只是轉身讓“調度員”做useState。

“調度程序”是一種處理以下事實的方法:可以使用多種不同的 react 方式,並且它們有時需要不同的鈎子實現。 例如,你可能在服務器上渲染,或者在 dom 上,或者在 react native 上,或者在自定義渲染器中。

在 react 的代碼庫中找到這些調度程序將是一件棘手的事情。 它們分布在不同的包中,因為只有那些包需要特定的實現。

此外,當你找到一個實現時,它會有很多函數的重用,因為它們做類似的事情。 useState 只是 useReducer 的一個特例,所以它將重用 useReducer 作為實現 useState 的一種方式。

話雖如此,當您調用setState時,以下是代碼可能最終出現的位置的一個示例

function basicStateReducer<S>(state: S, action: BasicStateAction<S>): S {
  // $FlowFixMe: Flow doesn't like mixed types
  return typeof action === 'function' ? action(state) : action;
}

action參數是您傳遞給 setState 的值或 function。 如果它是 function,它將調用它並傳入最新的 state,然后返回 function 返回的任何內容。 如果它不是 function,它只會返回你傳入的內容。這個返回值然后變成新的 state

暫無
暫無

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

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