ネストされた動的なフォームがあります。このフォームは、オーバーヘッド ガントリー クレーンを表すものです。
したがって、構造は次のようになります。
let equipmentInfo = {
bridges:[{
trolleys:[{
hoists:[{
}]
}]
}]
}
橋、トロリー、ホイストのフィールド セットごとに関数コンポーネントがあります。次のように、ツリー内の位置を説明する配列を渡します。
let keyPath = [['arrayLocation', indexOfEntry]] // [['bridge', 1], ['trolley',3], ['hoist', 0]]
私の質問は、この getObject 関数の使用に関するものです
const getObject = (object, location) => {
if(object == undefined) return {}
if(location.length == 0) return object
if(location.length == 1) return object[location[0][0]][location[0][1]]
if(location.length == 2) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]]
if(location.length == 3) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]][location[2][0]][location[2][1]]
if(location.length == 4) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]][location[2][0]][location[2][1]][location[3][0]][location[3][1]]
if(location.length == 5) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]][location[2][0]][location[2][1]][location[3][0]][location[3][1]][location[4][0]][location[4][1]]
if(location.length == 6) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]][location[2][0]][location[2][1]][location[3][0]][location[3][1]][location[4][0]][location[4][1]][location[5][0]][location[5][1]]
if(location.length == 7) return object[location[0][0]][location[0][1]][location[1][0]][location[1][1]][location[2][0]][location[2][1]][location[3][0]][location[3][1]][location[4][0]][location[4][1]][location[5][0]][location[5][1]][location[6][0]][location[6][1]]
}
次のように handleOnChange で使用されます。
const handleInputChange = (e, keyPath) => {
const { name, value } = e.target;
const object = {...equipmentInfo}
const targetObject = getObject(object, keyPath)
targetObject[name] = value
setObject(targetObject, object, keyPath)
setEquipmentInfo(object);
};
これを行うより良い方法はありますか?読みやすくするだけでなく、n 個のブランチをサポートするためです。
<BridgeFields
keyPath={newKeypath}
handleOnChange={handleOnChange}
equipmentInfo={EquipmentInfo}
setEquipmentInfo={setEquipentInfo}
/>
実装例は次のとおりです。
// inside <BridgeFields/>
getObject(equipmentInfo, keyPath).trolleys.map((trolly, index)) => {
// add to the keyPath the compenent and its index
let newKeyPath = [...keyPath, ["trolleys", index]]
// Form fields describing a bridge
<Form.Component
type='text'
name='serialNumber'
onChange={(e)=>{handleOnChange(e, newKeyPath)}
/>
// also include its child component fields (hoists, etc) .. like:
<HoistFields
keyPath={newKeypath}
handleOnChange={handleOnChange}
equipmentInfo={EquipmentInfo}
setEquipmentInfo={setEquipentInfo}
}
これは機能し、実際には非常に高速ですが、ここで行ったことを改善したいと考えています。この EquipmentInfo オブジェクトには他にもあります。改善したいと考えています。
アドバイスありがとうございます!