无法在反应打字稿中使用动态键访问状态值

时间:2021-06-14 12:21:30

标签: reactjs react-hooks react-typescript

    let [radioData, setRadioData] = React.useState({
      ActivityStatus: {
        Active: true,
        Inactive: false,
        Completed: false,
      },
      Other: {}
    })

    let options = [{ "label": "Active" }, { "label": "Inactive" }, { "label": "Completed" }]
    return (
      <div className="App">
        {options.map((item, index) => {
          return (
            <FormControlLabel
              control={
                <Checkbox
                  checked={radioData.ActivityStatus[item.label]}
                  name="gilad" />
              }
              label={item.label}
            />
          )
        })}
      </div>
    );

如果我试图访问检查的值,我会收到以下错误

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“{ Active: boolean;不活动:布尔值;完成:布尔值; }'。 在类型“{ Active: boolean;”上找不到带有“string”类型参数的索引签名。不活动:布尔值;完成:布尔值; }'。

2 个答案:

答案 0 :(得分:0)

您不需要将 ActivityStatus 对象作为反应状态,因为它似乎是恒定的。相反,根据需要在您的对象中保存状态键,并让 ActivityStatus 成为一个常量最终字典。 我已经创建了一个 codesandbox example,并且具有最小的可重现类似问题。看一看。

基本上我有:

const ActivityStatus =  {
  Active : true,
  Inactive : false,
  Completed : false,
}

我将状态字段保留在对象本身中。

答案 1 :(得分:0)

您应该像这样定义 string 作为对象键的类型:

    import "./styles.css";
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import React from 'react';
export default function App() {
  let [radioData, setRadioData] = React.useState<{[key:string]: boolean | any}>({
    ActivityStatus: {
      "Active": true,
      "Inactive": false,
      "Completed": false,
    },
    Other: {}
  })

  let options = [{ "label": "Active" }, { "label": "Inactive" }, { "label": "Completed" }]
  return (
    <div className="App">
      {options.map((item, index) => {
        return (
          <FormControlLabel
          control={
            <Checkbox
              checked={radioData.ActivityStatus[item.label]}
              name="gilad"
              onChange={() => 
                {
                  setRadioData({...radioData,
                     ActivityStatus: 
                     {...radioData.ActivityStatus,
                       [item.label]: !radioData.ActivityStatus[item.label]}})
                      }
                    } />
          }
          label={item.label}
        />
        )
      })}
    </div>
  );
}

检查它是否工作here