父组件渲染避免子组件重新渲染,使用memo将子组件包裹

    1. //子组件
    2. import React,{useState,memo} from 'react'
    3. import { Button } from 'antd';
    4. const Index=props=> {
    5. console.log('hhhhh');
    6. const getInitCounter=()=>{
    7. console.log('hhhyyy');
    8. return {number:props.number}
    9. }
    10. const [counter,setCounter]=useState(getInitCounter)
    11. const addOne=()=>{
    12. setCounter({number:counter.number+1})
    13. }
    14. const addTwo=()=>{
    15. setCounter(counter=>({number:counter.number+2}))
    16. }
    17. return (
    18. <>
    19. <p>{counter.number}</p>
    20. <Button onClick={addOne}> 点击按钮加一</Button>
    21. <Button onClick={addTwo}> 点击按钮加二</Button>
    22. </>
    23. )
    24. }
    25. // function (){
    26. // }
    27. export default memo(Index)
    1. //父组件
    2. import "antd/dist/antd.css";
    3. import Home from "../src/pages/Home";
    4. import { Button } from 'antd';
    5. import React,{useState} from 'react'
    6. function App() {
    7. const [name,setName]=useState('ws')
    8. const changeName=()=>{
    9. name==='ws'?setName('su'):setName('ws')
    10. }
    11. return (
    12. <>
    13. <p>{name}</p>
    14. <Home number={0} />
    15. <Button onClick={changeName}>点击改名</Button>
    16. </>
    17. );
    18. }
    19. export default App;