我在项目中实现了图片上传器。我正在上传的图片工作正常。然后,我希望将图像保存到redux存储而不是本地状态。
因此,我创建了我的动作和减速器并将其分派。我在使用控制台检查的reducer中获得了文件。而且我的商店也在更新,但是我没有在商店中获取文件,而是得到了空对象。
减速器
case 'UPDATE_IMAGEFILE_INFO':
return ({
...state,
myCustomTemplate: state.myCustomTemplate.map((panel) => {
if(panel.name === action.panelName){
return { ...panel, components: panel.components.map((component) => {
if(component.id === action.compId){
console.log(action.info);
return { ...component, imagefile: {...action.info}};
}
else{
return component;
}
})}
}
else{
return panel;
}
})
});
动作
export const updateImageFile = (info, panelName, compId) => {
return {
type: 'UPDATE_IMAGEFILE_INFO',
info,
panelName,
compId
}
}
组件
import React from 'react';
import {connect} from 'react-redux';
import { updateImageFile } from '../../actions/resumeBuilder';
class EditImageUpload extends React.Component{
constructor(props) {
super(props);
this.state = {
file: '',
imagePreviewUrl: ''
};
}
_handleSubmit(e) {
e.preventDefault();
this.props.dispatch(updateImageFile(this.state.file, this.props.match.params.pid, parseInt(this.props.match.params.id)));
}
_handleImageChange(e) {
e.preventDefault();
let file = e.target.files[0];
this.readImageFile(file);
}
readImageFile(file){
console.log(file);
let reader = new FileReader();
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
getInfo = () => {
if (this.state.imagePreviewUrl) {
return (<img src={this.state.imagePreviewUrl} />);
}
else {
return (<div className="previewText">Please select an Image for Preview</div>);
}
}
render() {
return (
<div className="previewComponent">
<form onSubmit={(e)=>this._handleSubmit(e)}>
<input className="fileInput" type="file" onChange={(e)=>this._handleImageChange(e)} />
<button className="submitButton" type="submit" onClick={(e)=>this._handleSubmit(e)}>Add</button>
</form>
<div className="imgPreview">
{this.getInfo()}
</div>
</div>
)
}
}
const ConnectEditImageUpload = connect()(EditImageUpload);
export default ConnectEditImageUpload;
如果您想要更多的代码,请提及。
Q1为什么状态更改没有反映任何内容? Q2我们可以将图像存储为文件吗?