首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用setState时,反应状态不变

使用setState时,反应状态不变
EN

Stack Overflow用户
提问于 2022-03-21 19:28:50
回答 1查看 54关注 0票数 -1

每当用户与其交互时,我都试图使开关启用/禁用。这是通过使用onChange事件来完成的,该事件随后更改上下文统计数据key, value

但是,当控制台记录输出时。政府似乎并没有改变。

上下文是以下值的对象,默认情况下,所有值都为null。更新后的上下文:

代码语言:javascript
复制
newSettings:
    anti_scam:
        enabled: null
        log_channel: null
        punishment_type: null

tmpSettings obj

代码语言:javascript
复制
newSettings:
    anti_scam:
        enabled: true
        log_channel: null
        punishment_type: null

如您所见,enabled的值发生了更改。但反应上下文状态不是。这意味着开关始终是禁用的,或者是启用的,这取决于用户的设置,而且他们不能更改它。

我尝试了,最初我使用的是可变的obj。但后来我发现,有时这不会引起重新呈现页面的反应。因此,我转而创建一个不可变的副本,并修改我希望从中更改的值。但这仍然没有解决问题。

任何帮助都将不胜感激。

代码语言:javascript
复制
const EnableSwitch = () => {
  const { context, setSaveEnabled } = useContext(SaveContext);
  const handleChange = (event) => {
    const tmpSettings = JSON.parse(JSON.stringify(context));
    tmpSettings.newSettings.anti_scam.enabled = event.target.checked;
    
    setSaveEnabled(tmpSettings);
  };

  return (
    <Fade bottom>
      <div>
        <Switch
          checked={context.newSettings.anti_scam.enabled}
          onChange={handleChange}
          inputProps={{ "aria-label": "controlled" }}
        />
      </div>
    </Fade>
  );
};

<SaveContext.Provider value={{ context, setSaveEnabled }}>

代码语言:javascript
复制
import { createContext } from "react";

const SaveContext = createContext({
    context: {
        saveEnabled: false,
        oldSettings: {
            anti_scam: {
                enabled: null,
                log_channel: null,
                punishment_type: null,
            }
        },
        newSettings: {
            anti_scam: {
                enabled: null,
                log_channel: null,
                punishment_type: null,
            }
        }
    },
    setSaveEnabled: () => { }
});

export const SaveProvider = SaveContext.Provider;
export default SaveContext;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-21 20:13:58

Context是从组件A到组件B获取值的一种方法,但是它不会为您实现其他任何东西。如果您希望将状态从组件A传递到组件B,则组件A将需要使用useState和其他此类代码实现该状态。因为您只是在使用默认值,所以这一切都不会发生。

因此,您需要在树顶附近制作一个组件,如下所示:

代码语言:javascript
复制
const Example = ({ children }) => {
  const [state, setState] = useState({
    saveEnabled: false,
    oldSettings: {
      anti_scam: {
        enabled: null,
        log_channel: null,
        punishment_type: null,
      },
    },
    newSettings: {
      anti_scam: {
        enabled: null,
        log_channel: null,
        punishment_type: null,
      },
    },
  });

  const contextValue = useMemo(() => {
    return {
      context: state,
      setSaveEnabled: /* some function which updates the state */,
    }
  }, [state]);

  return (
    <SaveContext.Provider value={contextValue}>
      {children}
    </SaveContext.Provider>
  )
};
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71563096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档