简体   繁体   English

使用 react usestate hook 将值存储在数组中

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

I have the following formik based example where I'm using primereact fileupload.我有以下基于 formik 的示例,其中我正在使用 primereact fileupload。 Everytime user uploads a file, the value of selectedAssetCategoryId is different.每次用户上传文件时, selectedAssetCategoryId的值都是不同的。 If a user is uploading multiple file at once then the value will remain the same.如果用户一次上传多个文件,则该值将保持不变。 For example, if a user is uploading 3 files together, the value of selectedAssetCategoryId will be 1.例如,如果用户同时上传 3 个文件,则selectedAssetCategoryId的值将为 1。

So I want to store value 1 three times in uploadedFileCategory array.所以我想在uploadedFileCategory数组中存储值1三次。

Is setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]);setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); a correct way of pusing items in the array?将项目放入数组的正确方法? When I'm hovering over the variable uploadedFileCategory on this line const [uploadedFileCategory, setUploadedFileCategory] = useState([]) , visual studio code editor is telling me that uploadedFileCategory is declared but its value is never read.ts(6133)当我将鼠标悬停在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)

Let me answer this:让我回答这个问题:

Question 1:问题一:

Is setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]);setUploadedFileCategory(uploadedFileCategory =>[...uploadedFileCategory,selectedAssetCategoryId]); a correct way of pusing items in the array?将项目放入数组的正确方法?

Answer It works and here is the example code:答案它有效,这里是示例代码:

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>
  );
}

The link is currently live at: https://byy0g5.csb.app/ Look at the console to see the logs.该链接当前位于: https://byy0g5.csb.app/查看控制台以查看日志。

Question 2问题2

When I'm hovering over the variable uploadedFileCategory on this line const [uploadedFileCategory, setUploadedFileCategory] = useState([]), visual studio code editor is telling me that uploadedFileCategory is declared but its value is never read.ts(6133)当我将鼠标悬停在 const [uploadedFileCategory, setUploadedFileCategory] = useState([]) 这一行的变量 uploadedFileCategory 上时,visual studio 代码编辑器告诉我 uploadedFileCategory 已声明,但其值从未被读取。ts(6133)

Answer It simply means that uploadedFileCategory is not being used anywhere in the code. Answer它只是意味着uploadedFileCategory没有在代码中的任何地方使用。

Even if the value is correctly set, you need to properly place this in the code to see the changes of value.即使正确设置了值,您也需要将其正确放置在代码中才能看到值的变化。 Try console.log(uploadedFileCategory) to see the output of the code.尝试console.log(uploadedFileCategory)查看代码的 output。

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

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