close

以按鈕點擊一次,數值會自動加1為例:

useState寫法:

import { useState } from "react";
 
function App() {
  const [val, setVal] = useState(0);
  const handleClick = () => {
    setVal(prev => prev + 1);
  };
  return (
    <>
      <div>{val}</div>
      <button onClick={handleClick}>Add</button>
    </>
  );
}
 
export default App;

useReducer寫法:

import { useReducer } from "react";
 
function App() {
  const initialState = { val: 0 };
  const myReducer = (state, action) => {
    switch (action.type) {
      case 'Add':
        return {
          ...state,
          val: state.val + 1
        };
    }
  }
  const [val, dispatch] = useReducer(myReducer, initialState);
  const handleClick = () => {
    dispatch({ type: 'Add' });
  };
 
  return (
    <>
      <div>{val.val}</div>
      <button onClick={handleClick}>Add</button>
    </>
  );
}
 
export default App;
arrow
arrow
    文章標籤
    React UseState useReducer
    全站熱搜

    deh3215 發表在 痞客邦 留言(0) 人氣()