react hook / react - 代码技巧

405 阅读1分钟
  1. setState
const [classifiedRule, setClassifiedRule] = React.useState<ClassifiedRule>({
    [RuleGroup.System]: [],
    [RuleGroup.Customize]: [],
    [RuleGroup.Exclude]: [],
  });
  
   const updateRule = (val: Rule[], group: RuleGroup) => {
    setClassifiedRule((prevClassifiedRule) => ({
      ...prevClassifiedRule,
      [group]: val,
    }));
  };


  1. 关于useState不更新的问题
  • 现象:
    1. defalutParam = {snapshotId: undefined},利用React.useState保存到state中。
      后来defalutParam 变为{snapshotId: "1111"},但是React.useState中的数据没有发生改变。
  • 解决: 利用React.useEffect
  const updateSearchParams = (params: Partial<FeedBackQuery>) => {
    setSearchParam({
      ...searchParam,
      ...params
    });
  };

  useDeepEqualEffect(() => {
    updateSearchParams(defalutParam);
  }, [defalutParam]);

  1. React.ReactNode还可以这样显示出来
 <PanelHeader
              title="系统推荐规则"
              desc="系统提供通用的敏感词表及算法模型,您可根据需求快速启用"
              ruleNumber={classifiedRule[RuleGroup.System].length}
              actions={[
                <Button
                  onClick={(e) => {
                    openDrawer(e, DrawerType.SystemRecommendDrawer);
                  }}
                  icon="plus"
                >
                  选用推荐规则
                </Button>,
              ]}
            />

export interface PanelHeaderProps {
  title: string;
  desc: string;
  ruleNumber: number;
  // 注意这行
  actions: React.ReactNode[];
}
export const PanelHeader: React.FC<PanelHeaderProps> = props => {
  const { title, desc, ruleNumber, actions } = props;

  return (
    <div className={styles.panelHeader}>
      <section>
        <h4>{title}</h4>
        <p className={styles.desc}>{desc}</p>
        <p>已添加 {ruleNumber} 组</p>
      </section>
      // 注意这行,React.ReactNode数组可以直接显示出来
      <section className={styles.panelActions}>{actions}</section>
    </div>
  );
};
  1. 可以直接渲染JSX.Element数组
// const renderTags: () => JSX.Element[]
return [
  ...showTags,
  <Popover content={hideTags}>
    <div className={styles.popContaienr}>
      <Tag>+{hideTags.length}</Tag>
    </div>
  </