react.memo react.lazy usememo usecallback
父元素更新,子元素不更新,memo,当props发生改变时才去更新子组件
function Parent() { const [count, setCount] = useState(1); const [val, setValue] = useState(''); const getNum = useCallback(() => { return Array.from({length: count * 100}, (v, i) => i).reduce((a, b) => a+b) }, [count]) return <View> <Child getNum={getNum} /> <View> <TouchableOpacity onPress={() => setCount(count + 1)}><Text>+1</Text></TouchableOpacity> <TextInput value={val} onChangeText={event => setValue(event)}/> </View> </View>; } const Child = React.memo(function ({ getNum }: any) { console.log(getNum) return <Text>总和:{getNum()}</Text> })
react中lazy api的用法,以及结合Suspense
const OtherComponent = lazy(() => new Promise(resolve => setTimeout(() => resolve( // 模拟ES Module { // 模拟export default default: function render() { console.log(111) return <Text>Other Component</Text> } } ), 3000 ) )); function MyComponent() { return ( <View> <Text>111111</Text> <Suspense fallback=<Text>11111</Text> > <OtherComponent /> </Suspense> </View> ); }
useCallback返回的是一个函数,usemome返回的是一个值
React.lazy配合 Suspense 使用可达到视图加载效果
const Foo = React.lazy(() => import('./BBB'));
<Suspense fallback={<Text>111</Text>}></Suspense>