每当用户与其交互时,我都试图使开关启用/禁用。这是通过使用onChange事件来完成的,该事件随后更改上下文统计数据key, value。
但是,当控制台记录输出时。政府似乎并没有改变。
上下文是以下值的对象,默认情况下,所有值都为null。更新后的上下文:
newSettings:
anti_scam:
enabled: null
log_channel: null
punishment_type: nulltmpSettings obj
newSettings:
anti_scam:
enabled: true
log_channel: null
punishment_type: null如您所见,enabled的值发生了更改。但反应上下文状态不是。这意味着开关始终是禁用的,或者是启用的,这取决于用户的设置,而且他们不能更改它。
我尝试了,最初我使用的是可变的obj。但后来我发现,有时这不会引起重新呈现页面的反应。因此,我转而创建一个不可变的副本,并修改我希望从中更改的值。但这仍然没有解决问题。
任何帮助都将不胜感激。
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 }}>
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;发布于 2022-03-21 20:13:58
Context是从组件A到组件B获取值的一种方法,但是它不会为您实现其他任何东西。如果您希望将状态从组件A传递到组件B,则组件A将需要使用useState和其他此类代码实现该状态。因为您只是在使用默认值,所以这一切都不会发生。
因此,您需要在树顶附近制作一个组件,如下所示:
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>
)
};https://stackoverflow.com/questions/71563096
复制相似问题