当子级改变状态时做出反应,父级重置状态

发布于 2025-01-17 14:31:40 字数 2666 浏览 0 评论 0原文

我在下面的摘要中有一个组件

import { FC, useState, useEffect, createContext, useContext } from 'react';
import { Button } from '@swvl/button';

type option = {
  name: string;
  icon?: JSX.Element;
};

type SwitchContentContextType = {
  options: option[];
  setOptions: (option: option[]) => void;
};

type SwitchContentCompoundTypes = {
  Content: FC<option>;
};

const SwitchContentContext = createContext({} as SwitchContentContextType);

export const SwitchContent: FC & SwitchContentCompoundTypes = ({ children }) => {
  const [options, setOptions] = useState<option[]>([]);

  useEffect(() => {
    console.log('options', options);
  }, [options]);

  return (
    <SwitchContentContext.Provider value={{ options, setOptions }}>
      <div
        sx={{
          backgroundColor: 'secondary-light-90',
          display: 'inline-flex',
          borderRadius: '20px',
          border: '1px solid transparent',
        }}
      >
        {options.map((option, index) => {
          return (
            <Button
              key={index}
              sx={{
                backgroundColor: 'secondary-light-90',
                borderRadius: 'inherit',
                color: 'content-quarternary',
                '&:hover, &:active': {
                  bg: 'secondary',
                  borderRadius: '20px',
                  color: 'primary-light-100',
                },
                '& span': { variant: 'text.p-small' },
              }}
            >
              {option.name}
            </Button>
          );
        })}
      </div>
      {children}
    </SwitchContentContext.Provider>
  );
};

const Content: SwitchContentCompoundTypes['Content'] = ({ children, name, icon, ...rest }) => {
  const { options, setOptions } = useContext(SwitchContentContext);

  useEffect(() => {
    const optionsCopy = [...options];
    optionsCopy.push({ name, icon });
    setOptions(optionsCopy);
  }, []);

  return <div {...rest}>{children}</div>;
};

SwitchContent.Content = Content;

时,尝试推动新选项的顶部选项状态应具有2个成员,但它只有最后一个成员。看来可以更改重新渲染父母的选项,并重新定义状态的原因,但是我所知道的是重新渲染不会重置

状态组件

<SwitchContent>
  <SwitchContent.Content name="Regular mode">
    <p>Content 1</p>
  </SwitchContent.Content>
  <SwitchContent.Content name="B2B mode">
    <p>Content 2</p>
  </SwitchContent.Content>
</SwitchContent>

我试图委托在父组件中登录使用效率的选项值,如下所示,

useEffect(() => {
  console.log('options', options);
}, [options]);

并在结果以下

I have the component in the snippet below

import { FC, useState, useEffect, createContext, useContext } from 'react';
import { Button } from '@swvl/button';

type option = {
  name: string;
  icon?: JSX.Element;
};

type SwitchContentContextType = {
  options: option[];
  setOptions: (option: option[]) => void;
};

type SwitchContentCompoundTypes = {
  Content: FC<option>;
};

const SwitchContentContext = createContext({} as SwitchContentContextType);

export const SwitchContent: FC & SwitchContentCompoundTypes = ({ children }) => {
  const [options, setOptions] = useState<option[]>([]);

  useEffect(() => {
    console.log('options', options);
  }, [options]);

  return (
    <SwitchContentContext.Provider value={{ options, setOptions }}>
      <div
        sx={{
          backgroundColor: 'secondary-light-90',
          display: 'inline-flex',
          borderRadius: '20px',
          border: '1px solid transparent',
        }}
      >
        {options.map((option, index) => {
          return (
            <Button
              key={index}
              sx={{
                backgroundColor: 'secondary-light-90',
                borderRadius: 'inherit',
                color: 'content-quarternary',
                '&:hover, &:active': {
                  bg: 'secondary',
                  borderRadius: '20px',
                  color: 'primary-light-100',
                },
                '& span': { variant: 'text.p-small' },
              }}
            >
              {option.name}
            </Button>
          );
        })}
      </div>
      {children}
    </SwitchContentContext.Provider>
  );
};

const Content: SwitchContentCompoundTypes['Content'] = ({ children, name, icon, ...rest }) => {
  const { options, setOptions } = useContext(SwitchContentContext);

  useEffect(() => {
    const optionsCopy = [...options];
    optionsCopy.push({ name, icon });
    setOptions(optionsCopy);
  }, []);

  return <div {...rest}>{children}</div>;
};

SwitchContent.Content = Content;

when try to push a new option top options state it should has 2 members but it only has the last one. it seems that change the options re-render the parent and this cause to redefine the state, but what I know is re-render will not reset the state so I need to know how to cause and how to fix this

below is how I use the component

<SwitchContent>
  <SwitchContent.Content name="Regular mode">
    <p>Content 1</p>
  </SwitchContent.Content>
  <SwitchContent.Content name="B2B mode">
    <p>Content 2</p>
  </SwitchContent.Content>
</SwitchContent>

I try to console log the options value in useEffect in the parent component like below

useEffect(() => {
  console.log('options', options);
}, [options]);

and got below result

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文