hooks useState更新對象

點擊2個按鈕,更新一個state對象,互不影響react

 

 

代碼:spa

import React, { useState } from 'react';

export default () => {
  const [state, setState] = useState({
    count: 0,
    count2: 0,
    name: 'aaa',
  });

  const click = () => {
    setState({
      ...state,
      count: state.count + 1,
    });
  };
  const change = () => {
    setState({
      ...state,
      name: 'bbb',
    });
  };
  return (
    <div>
      <div>
        count:{state.count},name:{state.name}
      </div>
      <button onClick={click}>+1</button>
      <button onClick={change}>name</button>
    </div>
  );
};
相關文章
相關標籤/搜索