簡體   English   中英

使用 react usestate hook 將值存儲在數組中

[英]storing values in an array using react usestate hook

我有以下基於 formik 的示例,其中我正在使用 primereact fileupload。 每次用戶上傳文件時, selectedAssetCategoryId的值都是不同的。 如果用戶一次上傳多個文件,則該值將保持不變。 例如,如果用戶同時上傳 3 個文件,則selectedAssetCategoryId的值將為 1。

所以我想在uploadedFileCategory數組中存儲值1三次。

setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); 將項目放入數組的正確方法? 當我將鼠標懸停在const [uploadedFileCategory, setUploadedFileCategory] = useState([])這一行的變量uploadedFileCategory上時,visual studio 代碼編輯器告訴我uploadedFileCategory is declared but its value is never read.ts(6133)

const DataRequestForm = (props) => {
    const user = JSON.parse(sessionStorage.loggedInUser)
    const {values, setFieldValue, touched, errors, isSubmitting, handleReset, handleChange} = props;
    const growl = React.createRef()
    
     const [uploadedFileCategory , setUploadedFileCategory] = useState([])

    
    
    // fileUpload function testing using new service
    const fileUpload = (e) => {
      

         //Store the values in an array.
         setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]);
      
        const personnelId = JSON.parse(sessionStorage.loggedInUser).id
        let formData = new FormData();
        e.files.forEach((file, i) => formData.append(`files`, file))

        axios.post('upms/uploadAndCreateAssociations?personnelId=' + personnelId +'&assetCategoryId='+selectedAssetCategoryId, formData,{
            headers: {
                "Content-Type": "multipart/form-data"
            }
        }).then((response) => {
            
            }).catch(err => console.log(err));


        }).catch((response) => {
            growlComp.show({severity: 'error', summary: 'File Upload unsuccessful', detail: 'File Upload was unsuccessful'})
            console.log('Could not upload files.....')
        })
      
    }
    

    

     
    
    

    return (
        <div>
            
            <div id="formDiv">
                <Growl ref={growl}/>
                <Form className="form-column-3">
                                         
                         
                    <div className="datarequest-form">   
                     <label style={{marginRight: '1355px',fontWeight: 'bold'}}>Document Upload</label>
                   
                    <div className="form-field">
                                <FileUpload
                                    name="files"
                                    mode='advanced'
                                    uploadHandler={fileUpload}
                                    customUpload={true}
                                    chooseLabel="Attach Files"
                                    maxFileSize="2058722381"
                                    ref={fileUploadRef}
                                    id="researcherAttachFileButton"
                                    disabled={disableButton}
                                    multiple={true}/>   
                                   
                             </div>

                       
                      
                       
                    </div>
                </Form>
            </div>
        </div>
    )

};

export const DataRequestEnhancedForm = withFormik(
    
    
    
    {

        
    mapPropsToValues: props => {

              
        
        return {
            
            uploadedFileCategory: uploadedFileCategory
            
        }
    },
    validationSchema:validationSchema,
    handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
      
        props.handleSubmit(values)
      
        setSubmitting(false)
    },
    setFieldValue(field, value, shouldVal) {
        console.log('In setFieldValue')
    },

    displayName: 'Data Request Form',
})(DataRequestForm)

讓我回答這個問題:

問題一:

setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); 將項目放入數組的正確方法?

答案它有效,這里是示例代碼:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [array, setArray] = useState([]);
  const changeArray = () => {
    console.log(array);
    setArray((b) => [...array, 1]);
  };
  return (
    <div className="App">
      <h1>Open console to see the logs</h1>
      <button onClick={() => changeArray()}>Example</button>
    </div>
  );
}

該鏈接當前位於: https://byy0g5.csb.app/查看控制台以查看日志。

問題2

當我將鼠標懸停在 const [uploadedFileCategory, setUploadedFileCategory] = useState([]) 這一行的變量 uploadedFileCategory 上時,visual studio 代碼編輯器告訴我 uploadedFileCategory 已聲明,但其值從未被讀取。ts(6133)

Answer它只是意味着uploadedFileCategory沒有在代碼中的任何地方使用。

即使正確設置了值,您也需要將其正確放置在代碼中才能看到值的變化。 嘗試console.log(uploadedFileCategory)查看代碼的 output。

暫無
暫無

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

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