簡體   English   中英

React js更新數組中的對象值,其中包含n個輸入數據useState

[英]React js update object value in an array with n number of input data useState

所以我正在用 react js 創建一個 todolist,該網站允許我在一個實例中添加多個任務,這意味着我可以添加任意數量的輸入字段並用數據填充它並保存它。 我的方法是使用預定義的 json 對象,每當我添加輸入字段時,useEffect 都會通過將預定義的 json 對象推送到數組中來處理它,而 useState 將設置新的數組。 這是我添加輸入字段或子項的代碼:

//hook for the input field/children count
   const [taskCount , setTaskCount] = useState(1);

//hook for all the input data, the initial data is an empty array
//whenever the taskCount increases, it will set a new array
const [test , setTest] = useState([]);

 //pre-defined json object schema
 const schema = 
   {   
       id : 0,
       choice : '',
       questName : '',
       location : '',
       time : '',
       linkedQuestB : '',
       linkedQuestA : '',
       status : [
                    {id : 'not_started' , label : 'not_started' , checked : false},
                    {id : 'in_progress' , label : 'in_progress' , checked : false},
                    {id : 'done' , label : 'done' , checked : false},
                ],

   }
//function onClick for adding input
//whenever a new input is created
//temp id is increment for input value onChange
  function addField () 
   {
       let initilaTest = test ;
       const temp = {...schema};
       temp.id = taskCount;
       initilaTest.push(temp);
       setTest(initilaTest);
    }

    useEffect(() => {
        addField();
        console.log(test)
    } , [taskCount])

const someExampleFunction () 
{
return (
                    <img 
                        src = {plus}
                        alt = {'exist non'}
                        onClick = {()=> setTaskCount(taskCount+ 1)}
                    />
             <exampleFunctionforInput > 
                {[...Array(taskCount)].map((value , index)=>{ return (<TodoFieldSet  id ={index} 
                 key = {index}
                update = {updateval} />)})}
            </exampleFunctionforInput >)}

因此,要更改每個相應輸入中的值,我使用 onChange 方法。 處理 onChange 方法的方法如下,每當輸入值發生變化時,onChange 將觸發更新函數,該函數將索引作為參數 id 和 event.target 的參數以循環更改相應的輸入值object 並匹配 e.target.id 並最終更改test的狀態。 它確實有效,但很明顯,每當輸入字段的數量增加時,在輸入字段中輸入的速度就會變慢,因為數組中有大量對象可以循環遍歷並找到相應的數據。 那么有沒有更好的方法來做到這一點。 輸入字段組件的代碼:

 const inputProps = 
    [   
        {id : 'questName' , name : 'Quest Name',type :'text' , },

        {id : 'time' , name : 'Time',type :'text' ,},

        {id : 'linkedQuestB' , name : 'Linked Quest Before',type : 'text',},

        {id : 'linkedQuestA' , name : 'Linked Quest After',type : 'text',},

        {id : 'location' , name : 'location',type : 'text',},
    ]
//handling the onChange
   const updateval = (index , target  ) => 
    {
        let temp = [...test];
        for(let key in temp[index])
        {
            if(key === target.id )
            {
                temp[index][key] = target.value;
            }
        }
        setTest(temp);
        
        
    }
function exampleFunctionforInput ({id , update})
{
return (
{inputProps && inputProps.map((value , index)=> 
            {   
               return (  
               <TodoInWrapper  key = {index} id = {value.name + id}>
                    <label htmlFor = {value.id}>{value.name}</label>
                    <input 
                        id = {value.id} 
                        type = {value.type}
                        onChange = {e => update(id , e.target)}
                        />
                </TodoInWrapper>)
            })};)
}

不要介意所有的 React Components 標簽,它們都是樣式化的組件。

您正在遍歷所有元素以找到該元素然后更新它,如果您想避免這種情況,您可以使用鍵值映射,這將提高從 O(n) 到 O(1) 的性能

可以進行其他可能的優化,我相信這會有所作為:

  1. 消除突變
  2. 使函數純(它們有副作用)
  3. React 中組件的名稱應該以大寫字母開頭
  4. 將更多可預測的鍵傳遞給TodoInWrapper
  5. 對組件內的函數使用 useCallback

我無法給出示例代碼,因為提供的代碼很難用作參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM