使用 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>
);
}
link 目前直播于:https://byy0g5.csb.app/
查看控制台以查看日志。
问题二
当我将鼠标悬停在该行的变量 uploadedFileCategory 上时 const [uploadedFileCategory , setUploadedFileCategory] = useState([]), visual studio 代码编辑器告诉我已声明 uploadedFileCategory 但是它的值永远不会是 read.ts(6133)
回答
它只是意味着代码中的任何地方都没有使用 uploadedFileCategory
。
即使正确设置了值,您也需要将其正确放置在代码中才能看到值的变化。
尝试 console.log(uploadedFileCategory)
查看代码的输出。
我有以下基于 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>
);
}
link 目前直播于:https://byy0g5.csb.app/ 查看控制台以查看日志。
问题二
当我将鼠标悬停在该行的变量 uploadedFileCategory 上时 const [uploadedFileCategory , setUploadedFileCategory] = useState([]), visual studio 代码编辑器告诉我已声明 uploadedFileCategory 但是它的值永远不会是 read.ts(6133)
回答
它只是意味着代码中的任何地方都没有使用 uploadedFileCategory
。
即使正确设置了值,您也需要将其正确放置在代码中才能看到值的变化。
尝试 console.log(uploadedFileCategory)
查看代码的输出。