我在我的项目中实现了一个图像上传器。我上传的图像工作正常。然后我希望将图像保存到 redux 存储而不是本地状态。
所以我创建了我的动作和减速器并发送了它。我在使用控制台检查的减速器中获取了我的文件。我的商店也在更新,但我没有在商店中获取文件,而是得到空对象。
减速机
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 我们可以将图像存储为文件吗?
据我了解,redux devtools 无法显示文件。图像存储在状态中,但是由于开发工具无法向您显示这一点,因此它将传递一个空对象。
将图像传递给reducer后尝试
console.log(image)
,它应该存储在reduxt状态中。