React管理系统开发踩坑

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

1 antd Table组件改变dataSource数据源但并没有重新渲染

Table只有在rowKey发生变化时才会改变因此rowKey需要改变

<Table rowKey={item => item.name+ Date.now()}/>

2 使用useEffect陷入无限循环

由于在useEffect中使用setState更新了数据使页面重新经历componentDidUpdate生命周期因此会再次调用useEffect导致陷入循环中

解决办法让useEffect绑定依赖项

useEffect(()=>{
	setData(data)
},[dialogData])

3 将antd表格导出为excel

使用js-export-excel,在使用import导入时需要先在.d.ts文件中进行声明

//declare module 'js-export-excel'
let options = {}
options.fileName = ''
options.datas = [
	sheet
]

4 使用setState改变对象属性和数组属性

setUser({
	...user,
	name: 'xie'
})


setArr([...arr,4])

5 useRef和useState的区别

可以直接在函数中获取到改变的ref值useRef改变值不会引起页面的重新渲染而useState会

const ref = useRef(0)

const handleClick = ()=>{
	ref.current = ref.current + 1
}

6 对自定义组件使用ref

interface Props{
	children: ReactNode
}

type Ref = HTMLInputElement


const MyInput= forwardRef<Props,Ref>((props,ref)=>{
	return <input {...props} ref={ref}/>
})

7 useReducer

useState中存在的问题依然存在


interface InitialState{
	name:string
}

interface ActionType {
	type: 'change'| 'increment' | 'reset'
	payload: string | number
}

const initialState = { name:'111'}
const reducer = (state:InitialState,action:ActionType):StateType=>{
	switch (action.type){
		case 'change':
			return [...state,name:'xie']
			break
		default:
			break
	}
	return initialState
}

const [state,dispatch]=useReducer(reducer,initialState)

const handleChange = ()=>{
	dispatch({type: 'change'})
}


8 useContext

当多个组件同时使用同一个context又不希望都变化

const NumContext = createContext<number|undefined>(undefined)

const Com = ()=>{
	const num = useContext(NumContext)
	return(
		<div>{num}</div>	
	)
}

const Counter = ()=>{
	const num = useContext(NumContext)
	return <div>
		<NumContext.Provider value = {num}>
			<Com/>
		</NumContext.Provider>
		</div>
}

const Hook = ()=>{
	return(
		<NumContext.Provider value = {num}>
			<Counter/>
		</NumContext.Provider>
	)
}

9 useMemo

适用于有大量数据渲染时依赖缓存

const visible = useMemo(()=>filterNodes(todes,tab),[todes,tab])
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6