React Hooks如何主动更新Hooks组件
作者:Franklin___
这篇文章主要介绍了React Hooks如何主动更新Hooks组件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
React Hooks主动更新Hooks组件
当我们用useState创建对象数组的时候,使用数组的index去改变数组某一项中的对象属性时,useState无法监听到,此时视图就无法更新,所以我们就需要主动强制更新视图
const [friendCircleArr, setFriendCircleArr] = useState({ name: 'Lucy', avator: P1, content: { text: '今天上课好累啊', image: null }, time: '刚刚', isLike: false }, { name: 'Helena', avator: P2, content: { text: '杰伦太帅了吧!!', image: [Zhou1, Zhou2, Zhou3] }, time: '1分钟前', isLike: false })
此时我们去修改此对象数组
const likeClick = index => { const tempArr = friendCircleArr tempArr[index].isLike = !tempArr[index].isLike setFriendCircleArr(tempArr) }
我们会发现视图并没有发生更新
此时我们就需要主动更新视图
const [refresh, setRefresh] = useState(false) useEffect(() => { refresh && setRefresh(false) }, [refresh]) // 修改之前的代码 const likeClick = index => { const tempArr = friendCircleArr tempArr[index].isLike = !tempArr[index].isLike setFriendCircleArr(tempArr) setRefresh(true) }
创建一个refresh变量,用来控制视图更新,此时再调用likeClick方法,视图就可以正常更新了
react hooks更新、刷新子组件
import React, { Fragment, useEffect, useState, } from 'react'; import { Tabs, Button, } from 'antd'; import { connect, history } from 'umi'; import Cmp1 from './components/cmp1'; import Cmp2 from './components/cmp2'; import Cmp3 from './components/cmp3'; import Cmp4 from './components/cmp4'; import Cmp5 from './components/cmp5'; import Cmp6 from './components/cmp6'; const { TabPane } = Tabs; const DemoPage = () => { const [refresh, setRefresh] = useState(false); useEffect(() => { refresh && setTimeout(() => setRefresh(false)); }, [refresh]); // tab切换 const handleTabChange = (key) => { setCurrentKey(key); }; //刷新,重新加载组件 const handleReload = () => { setRefresh(true); }; return ( <Fragment> <div> <Button onClick={handleReload}>刷新</Button> <div> <Tabs activeKey={currentKey} onChange={handleTabChange}> <TabPane tab="1" key="1"></TabPane> <TabPane tab="2" key="2"></TabPane> <TabPane tab="3" key="3"></TabPane> <TabPane tab="4" key="4"></TabPane> <TabPane tab="5" key="5"></TabPane> <TabPane tab="6" key="6"></TabPane> </Tabs> {currentKey === '1' && !refresh && ( <Cmp1/> )} {currentKey === '2' && !refresh && ( <Cmp2/> )} {currentKey === '3' && !refresh && ( <Cmp3/> )} {currentKey === '4' && !refresh && ( <Cmp4/> )} {currentKey === '5' && !refresh && ( <Cmp5/> )} {currentKey === '6' && !refresh && ( <Cmp6/> )} </div> </div> </Fragment> ); }; export default connect()(DemoPage);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。