我想更改状态数据的名称,年龄,国家/地区的查询部分。
... {数据:{... state.data,[键] .query:e.target.value}},但是在[键] .query处,解析错误:':'expected.eslint。它将结束。
我该如何解决?
如果有人知道,请告诉我。
interface Data {
name?: Name;
age?: Age;
country?: Country;
}
interface Name {
query: string;
current: boolean;
}
interface Age {
query: string;
current: boolean;
}
interface Country {
query: string;
current: boolean;
}
const initial: Name | Age | Country = {
query: '',
current: false,
};
const initialdata: Data = {
name: initial,
age: initial,
country: initial,
}
interface State {
data: Data;
text: string;
modal: boolean
}
const Index: FC = () => {
const [state, setState] = useState<State>({
data: initialdata,
text: '',
modal: false,
});
// Where to call this function, one of Data's name, age, country is passed like onChangeWithKey (ChangeEvent <HTMLInputElement>,'name').
const onChangeWithKey = (e: any, key: string) => {
setState({ ...state, ...{data: { ...state.data, [key].query: e.target.value } } });
};
答案 0 :(得分:1)
[key].query
不是有效的对象密钥。另外,请确保您维护state.data
属性。
const onChangeWithKey = (e: any, key: string) => {
setState({
...state, // <-- copy state
data: {
...state.data, // <-- copy state.data
[key]: { // <-- update specific key property
...state.data[key], // <-- copy state.data[key]
query: e.target.value // <-- update query property
},
} ,
});
};