父组件渲染避免子组件重新渲染,使用memo将子组件包裹
//子组件
import React,{useState,memo} from 'react'
import { Button } from 'antd';
const Index=props=> {
console.log('hhhhh');
const getInitCounter=()=>{
console.log('hhhyyy');
return {number:props.number}
}
const [counter,setCounter]=useState(getInitCounter)
const addOne=()=>{
setCounter({number:counter.number+1})
}
const addTwo=()=>{
setCounter(counter=>({number:counter.number+2}))
}
return (
<>
<p>{counter.number}</p>
<Button onClick={addOne}> 点击按钮加一</Button>
<Button onClick={addTwo}> 点击按钮加二</Button>
</>
)
}
// function (){
// }
export default memo(Index)
//父组件
import "antd/dist/antd.css";
import Home from "../src/pages/Home";
import { Button } from 'antd';
import React,{useState} from 'react'
function App() {
const [name,setName]=useState('ws')
const changeName=()=>{
name==='ws'?setName('su'):setName('ws')
}
return (
<>
<p>{name}</p>
<Home number={0} />
<Button onClick={changeName}>点击改名</Button>
</>
);
}
export default App;