首页 > 解决方案 > 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() 更改其类型即可。但不应该只通过改变类型来直接改变吗?

期待帮助。

标签: reactjsreact-hooks

解决方案


我认为没有必要有重复的数据。删除对象type中的键chart

无论如何,您可以在 useEffect 中设置选项:

useEffect(() => {

  setOptions({...options, chart: {...options.chart, type}};

  // ... your code ... //

},[type]);

推荐阅读