[英]Best way to define a subarray of state with consideration of react/destructuring-assignment
我想定義一個包含兩個值 state 的新數組。這個數組將被發送到 api。我的第一個工作正常的方法是:
const userRoles = {
userName: this.state.userName,
roles: this.state.userRoles
};
putData('api/User/EditUserRoles', userRoles).then((result) => {
const responseJson = result;
if (responseJson) {
this.setState({ msg: "User's roles updated successfully!" });
}
});
但是在我啟用eslint - react/destructuring-assignment之后出現了以下錯誤:
所以我將代碼更改為
const { userName, userRoles } = this.state;
const userNameBuffer = userName;
const userRolesBuffer = userRoles;
const userRolesArrayBuffer = {
userName: userNameBuffer,
roles: userRolesBuffer
};
putData('api/User/EditUserRoles', userRolesArrayBuffer).then((result) => {
const responseJson = result;
if (responseJson) {
this.setState({ msg: "User's roles updated successfully!" });
}
});
哪個有效,但我對使用額外的“緩沖區”變量不滿意。 有沒有辦法在考慮反應/解構賦值的情況下將這段代碼寫得更“漂亮”(例如,沒有“緩沖”變量)?
感謝您的每一個回答,對於我的英語可能出現的任何錯誤,我們深表歉意。
您不需要將變量保存在緩沖區中,更優雅和常見的方法是:
const { userName, userRoles } = this.state;
const userRolesBuffer = {
userName, // its not mistake, in object variables with same name can be assigned like this
roles: userRoles
};
putData('api/User/EditUserRoles', userRolesBuffer).then((result) => {
const responseJson = result;
if (responseJson) {
this.setState({ msg: "User's roles updated successfully!" });
}
});
好吧,答案似乎很簡單,我誤解了一些東西。
我認為有必要像這樣聲明一個數組
const exampleArray = {
key1: "value1",
key2: "value2"
}
JSON.stringify(exampleArray) 的結果; 好像
{
"key1": "value1",
"key2": "value2"
}
但似乎是這樣
const key1 = "value1";
const key2 = "value2";
const exampleArray = {
key1,
key2,
}
確實返回相同的結果...
所以我的代碼,匹配的 react/destructuring-assignment 最終看起來像
const { userName, userRoles } = this.state;
const roles = userRoles;
putData('api/User/EditUserRoles', { userName, roles }).then((result) => {
const responseJson = result;
if (responseJson) {
this.setState({ msg: "User's roles updated successfully!" });
}
});
感謝您的回答...尤其是 Pavlo Demydiuk ^^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.