目录
重复渲染
简介:在 react 中 props 和state改变时,子组件会重新渲染
React.memo()
简介:子组件不操作props和state 使用 React.memo() 控制子组件重复渲染
- React v16.6引进来的新属性,用来控制函数组件的重新渲染
- 将组件作为函数(memo)的参数,函数的返回值(Child)是一个新的组件
例子
import * as React from "react";
import { View, Button, Text } from "@tarojs/components";
const UseChild: React.FC = React.memo(() => {
console.log("渲染了11111");
return <View>子1</View>;
});
const UseChild2: React.FC = React.memo(() => {
console.log("渲染了2222");
return <View>子2</View>;
});
const UseTest: React.FC = () => {
const [state, setState] = React.useState(0);
const add = () => {
// 只会渲染一次
setState(val => val + 1);
};
return (
<View>
<Text>{state}</Text>
<Button onClick={add}>支付</Button>
<UseChild></UseChild>
<UseChild2></UseChild2>
</View>
);
};
export default UseTest;
React.useMemo
简介:如果参数是对象,使用 React.useMemo 控制子组件重复渲染
例子
import * as React from "react";
import { View, Button, Text } from "@tarojs/components";
// === 父组件 ===
const UseTest: React.FC = () => {
const [count, setCount] = React.useState(0);
const increment = () => {
setCount(count + 1);
};
// 备注:如果是 useState 解构的 子组件不会重复渲染
// const [userInfo, setUserInfo] = useState({ name: "小明", age: 18 });
// const userInfo = { name: "小明", age: 18 }; 子组件会重复渲染
const userInfo = React.useMemo(() => ({ name: "小明", age: 18 }), []);
return (
<View>
<Button onClick={increment}>点击次数:{count}</Button>
<UseChild userInfo={userInfo}></UseChild>
</View>
);
};
// === 子组件 ===
const UseChild: any = React.memo((props: any) => {
const { userInfo } = props;
console.log("渲染了11111", userInfo);
return (
<View>
<View>{userInfo.name}</View>
<View>{userInfo.age}</View>
</View>
);
});
export default UseTest;
React.useMemo 也可以绑定 jsx和tsx对象
const TestChild: React.FC = React.memo(props => {
console.log("渲染 1111");
return (
<View>
<Text>child 组件 </Text>
{props.children}
</View>
);
});
const TestParent: React.FC = () => {
const [state, setState] = React.useState(0);
// 子组件只会渲染一次
const el = React.useMemo(() => {
return <View>22222</View>;
}, []);
return (
<View>
<Button onClick={() => setState(state + 1)}>点击次数{state}</Button>
<TestChild>{el}</TestChild>
</View>
);
};
React.useCallback()
- 改变父元素的state值,近而渲染父组件
- 父组件渲染时,会重新渲染onclick事件,近而连锁反应,被动传值给子组件,导致子组件渲染
- 如果props传入的是 基础数据类型,子组件不会渲染
例子
import * as React from "react";
import { View, Button, Text } from "@tarojs/components";
// === 父组件 ===
const UseTest: React.FC = () => {
const [name, setName] = React.useState("zhangds");
// 会重复渲染子组件
// const click = () => {
// setName(name);
// };
// 只会渲染一次
const click = React.useCallback((name: string) => {
setName(name);
}, []);
return (
<View>
<Text>{name}</Text>
<UseChild name="zhangds" click={click}></UseChild>
</View>
);
};
// === 子组件 ===
const UseChild: any = React.memo((props: any) => {
const { name, click } = props;
console.log("渲染了11111", name);
return (
<View>
<Button onClick={() => click("zhudachang")}>sss</Button>
</View>
);
});
export default UseTest;
标签:React,const,name,渲染,hooks,react,组件,return
From: https://www.cnblogs.com/sjie/p/17227786.html