reactjs - React 不能将一个 var 的更改引用到嵌套对象中的另一个 var
问题描述
我在嵌套对象中使用外部变量状态时遇到了困难。
例如,假设我有这两种状态:
const [type, setType] = useState('line');
const [options, setOptions] = useState({
id: 1,
chart: {
events: {
load: function () {
let btn = document.getElementsByClassName('btn');
let chart = this;
for(let btntmp of btn) {
if(btntmp.id=='area' || btntmp.id=='pie' || btntmp.id=='bar' || btntmp.id=='line' || btntmp.id=='column') {
btntmp.addEventListener('click', () => {
Type = btntmp.id;
//setType(Type);
//
for(let i=0;i<chart.series.length;i++) {
chart.series[i].update({ type: Type});
}
});
chart.redraw();
}
}
},
},
type: type,
},});
setType('bar');
useEffect(() => {
console.log(options.chart.type); ---> prints 'line'
if (type == 'pie') {
console.log('its pie');
setEndPeriodSelected(null);
setShown(false);
} else {
setShown(true);
}
},[type]);
运行代码时,type 将获得默认值 'line',当调用 setType 时,type 会更改,但 options.chart.type 不会获得其新值。
我已经想出了传播选项的解决方案,然后只需使用 setOptions() 更改其类型即可。但不应该只通过改变类型来直接改变吗?
期待帮助。
解决方案
我认为没有必要有重复的数据。删除对象type
中的键chart
。
无论如何,您可以在 useEffect 中设置选项:
useEffect(() => {
setOptions({...options, chart: {...options.chart, type}};
// ... your code ... //
},[type]);
推荐阅读
- spring-boot - 在@Document indexName中使用的SpEL与spring数据elasticsearch和spring boot没有被解析
- javascript - Mongo DB mapReduce() : E QUERY [js] TypeError: c.out is undefined
- php - 类 stdClass 的错误对象无法转换为字符串,不要让我在 laravel 6.0 中从我的数据库中删除一个项目
- loops - Sumif在excel中循环请
- python - 如何在 Linux 上使用 Python 打开 Jupyter 工作目录下的目录中的文件?
- javascript - 在 react-admin 中,如何根据我的数据更改 showButton 的标签?
- android - 如何在设置中断开蓝牙连接而不取消配对
- sql - SQL 显示 MIN() 列并显示其他列
- regex - 如果第一个英文字母尚未大写,则使用正则表达式将其大写
- ios - SwiftUI 无法删除选取器上方的空间 - 表单版本