简体   繁体   English

如何在 React 中使用 state 值动态地将新属性添加到文件 object

[英]How to add new Properties to File object in React with state value dynamically

I hope to be descriptive, Let's say I have a Files Object Array我希望是描述性的,假设我有一个文件 Object 数组

JSONfiledata = [
    {
      lastModified:123444,
      name: 'file1',
      size: 0,
      type: ""    
    },
    {
      lastModified:123445,
      name: 'file2',
      size: 0,
      type: ""    
    },
    {
      lastModified:123446,
      name: 'file3',
      size: 0,
      type: ""    
    }
]

And I have a this component that receives that data through props我有一个通过 props 接收数据的组件

import React, {useState} from 'react'

const component = ({files}) => {

   const [inputValue, setInputValue] = useState('')

   const eventHandler = (e) => setInputValue(e.target.value)

   const addNewKey = files.map(fileObj => Object.defineProperty(fileObj, 'newKey', {
      value: inputValue
   }))

   return (
     {
       files.map(fileData => (<div>
          {fileData.name}
          <input value={inputValue} onChange={setInputValue} />
       </div>))
     }
   )
}

How can I mutate the current files object and add a 'newKey' on each one depending on the inputValue, but independently from each other.如何改变当前文件 object 并根据 inputValue 在每个文件上添加一个“newKey”,但彼此独立。

I mean, at position 0 let's say I write on the input "this is the file number one" at position 1 "this is the file number two" and so on....我的意思是,在 position 0 假设我在 position 1 的输入“这是第一个文件”上写下“这是第二个文件”等等....

At the end, the expected output will be最后,预期的 output 将是

[
    {
      lastModified:123444,
      name: 'file1',
      size: 0,
      type: "",
      newKey: "this is the file number one"    
    },
    {
      lastModified:123445,
      name: 'file2',
      size: 0,
      type: "",
      newKey: "this is the file number two"     
    },
    {
      lastModified:123446,
      name: 'file3',
      size: 0,
      type: "" ,
      newKey: "this is the file number three"    
    }
]

I build a solution: Build another component to manage every file individualy.我构建了一个解决方案:构建另一个组件来单独管理每个文件。 Like this:像这样:

import React, { useState } from 'react';

import { Map } from './Map';

export const MapList = ({ files }) => {
  const [filesState, setFilesState] = useState([...files]);

  const handleChange = nObject => {
    /**You can compare with a unique id, preferably */
    setFilesState(filesState => filesState.map(file => (file.name === nObject.name ? nObject : file)));
  };
  return (
    <div>
      {filesState.map(file => (
        // If you have an ID you can send in this plance, to be more simple find the object in the handle function
        <Map handleChange={handleChange} file={file} />
      ))}
      <h2>Files Change</h2>
      {filesState.map(file => (
        <div>
          <p>
            {file.name} {file.newKey && file.newKey}
          </p>
        </div>
      ))}
    </div>
  );
};

In this wrapper component, you will update the entry array, with the handleChange function.在这个包装器组件中,您将使用 handleChange function 更新条目数组。

After you can build a component to manage your new key, for example:在您可以构建一个组件来管理您的新密钥之后,例如:

import React, { useState } from 'react';

export const Map = ({ file, handleChange }) => {
  const [input, setInput] = useState('');

  const handleChangeKey = e => {
    const { name, value } = e.target;
    const nFile = { ...file, [name]: value };
    setInput(value);
    handleChange(nFile);
  };
  return (
    <div>
      <div>
        <label htmlFor={file.name}>
          <small>Input for: {file.name}</small>{' '}
        </label>
        <input id={file.name} name='newKey' value={input} onChange={handleChangeKey} type='text' />
      </div>
    </div>
  );
};

It works for me, i think is a solution maybe not the best, but is a simple solutions.它对我有用,我认为这可能不是最好的解决方案,而是一个简单的解决方案。

const JSONfiledata = [
    {
      lastModified:123444,
      name: 'file1',
      size: 0,
      type: ""    
    },
    {
      lastModified:123445,
      name: 'file2',
      size: 0,
      type: ""    
    },
    {
      lastModified:123446,
      name: 'file3',
      size: 0,
      type: ""    
    }
];

const fileNameToUpdate = 'file2';
const newKey = "file2Key";
const newArray = JSONfiledata.map((item) => {
    if (item.name === fileNameToUpdate) {
        return {...item, newKey: newKey };
    } else {
        return item;
    }
});

console.log(`newArray==`, newArray);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM