react复习
- 生命周期:componentWillReceiveProps
- 钩子函数:usestate,useeffect,usecallback,usememo
- 属性:useRef 和 createRef
- 拖拽库:react-dnd
componentWillReceiveProps
componentWillReceiveProps(nextProps) {
this.setState({
slotId: nextProps.slotId,
currentMaterialId: 0
});
this.fetchData(nextProps.slotId)
}
- 当props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用
react hooks—usestate,useeffect,usecallback,usememo
- useCallback 建议当做最佳实践来用,也就是你指的大量使用,这个比较符合直觉
要缓存依赖未改变的回调函数之外(与 useMemo 类似),重要的是为了能够在依赖发生变更时,能够确保回调函数始终是最新的实例- useMemo 使用时,要仔细评估其代价: 如果存在依赖,只在依赖变化时重新创建,不存在依赖,那就只创建一次
补充 React.memo 参考 PureComponent
useRef 和 createRef 的区别
[1] https://blog.csdn.net/frontend_frank/article/details/104243286
同: 实现一个需求 – 点击 button 的时候 input 设置焦点. 此时两者都可以用来表示ref属性
不同: createRef 每次渲染都会返回一个新的引用,而 useRef 每次都会返回相同的引用。
-
useRef 不仅仅是用来管理 DOM ref 的,它还相当于 this , 可以存放任何变量.
-
useRef 可以很好的解决闭包带来的不方便性. 你可以在各种库中看到它的身影, 比如 react-use 中的 useInterval , usePrevious
值得注意的是,当 useRef 的内容发生变化时,它不会通知您。更改.current属性不会导致重新呈现。 因为他一直是一个引用 .
react-dnd 拖拽库
- useDrag, useDrop
- tabs中–实现可拖拽标签
import { DndProvider, useDrag, useDrop, createDndContext } from 'react-dnd';
// const RNDContext = createDndContext(HTML5Backend);
const type = 'DragableBodyRow';
const DragableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
const ref = useRef();
const [{ isOver, dropClassName }, drop] = useDrop({
accept: type,
collect: monitor => {
const { index: dragIndex } = monitor.getItem() || {};
if (dragIndex === index) {
return {};
}
return {
isOver: monitor.isOver(),
dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
};
},
drop: item => {
moveRow(item.index, index);
},
});
const moveRow = useCallback(
(dragIndex, hoverIndex) => {
const dragRow = data[dragIndex];
let copyedData = [...data];
copyedData.splice(dragIndex, 1);
copyedData.splice(hoverIndex, 0, dragRow);
setData(copyedData);
onSort(copyedData.map((e, index) => ({id: e.id, sort: index})))
},
[data],
);
const [, drag] = useDrag({
item: { type, index },
collect: monitor => ({
isDragging: monitor.isDragging(),
}),
});
drop(drag(ref));
return (
<tr
ref={ref}
className={`${className}${isOver ? dropClassName : ''}`}
style={{ cursor: 'move', ...style }}
{...restProps}
/>
);
};
const DragSortingTable = ({ list, columns, rowSelection, onSort }) => {
const [data, setData] = useState(list);
const components = {
body: {
row: DragableBodyRow,
},
};
return (
<Table
rowKey="id"
columns={columns}
dataSource={data}
components={components}
pagination={false}
rowSelection={rowSelection}
onRow={(record, index) => ({
index,
moveRow,
})}
/>
);
};