[javascript] Redux에서 파일 업로드 방법은?
- 파일 업로드 동작을 위한 액션 생성자를 만듭니다. 예를 들어,
uploadFile
액션을 생성하는 액션 생성자를 작성합니다.
export const uploadFile = (file) => {
return {
type: 'UPLOAD_FILE',
payload: file
};
};
- 리듀서 함수에서 파일 업로드를 처리합니다. 액션 타입에 따라 상태를 업데이트하고, 파일을 서버로 전송하는 로직을 작성합니다. 예를 들어,
UPLOAD_FILE
액션을 처리하는 리듀서를 작성합니다.
const initialState = {
file: null,
uploading: false,
error: null
};
const fileReducer = (state = initialState, action) => {
switch (action.type) {
case 'UPLOAD_FILE':
// 파일 업로드 시작 상태로 변경
return {
...state,
uploading: true,
error: null
};
case 'UPLOAD_FILE_SUCCESS':
// 파일 업로드 성공 시 상태 업데이트
return {
...state,
file: action.payload,
uploading: false,
error: null
};
case 'UPLOAD_FILE_FAILURE':
// 파일 업로드 실패 시 상태 업데이트
return {
...state,
uploading: false,
error: action.payload
};
default:
return state;
}
};
export default fileReducer;
- 파일 업로드 컴포넌트에서 파일을 선택하고 업로드 액션을 디스패치합니다. 예를 들어, 파일 선택 버튼과 파일 업로드 버튼이 있는 컴포넌트를 작성합니다.
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { uploadFile } from './actions';
const FileUploadComponent = () => {
const [selectedFile, setSelectedFile] = useState(null);
const uploading = useSelector(state => state.file.uploading);
const dispatch = useDispatch();
const handleFileChange = (e) => {
setSelectedFile(e.target.files[0]);
};
const handleFileUpload = () => {
if (selectedFile) {
dispatch(uploadFile(selectedFile));
}
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleFileUpload} disabled={uploading}>
{uploading ? 'Uploading...' : 'Upload File'}
</button>
</div>
);
};
export default FileUploadComponent;
이와 같이 Redux를 사용하여 파일 업로드를 처리할 수 있습니다. 액션 생성자와 리듀서를 사용하여 파일 업로드 동작을 관리하고, 컴포넌트에서 액션을 디스패치하여 파일 업로드를 시작할 수 있습니다.
참고 자료:
- Redux 공식 문서: https://redux.js.org/
- React Redux 공식 문서: https://react-redux.js.org/