我有一个包含几个页面的应用程序,主要的App
组件保存使用发送到页面的回调在所有页面上进行的所有更改的状态。
应用程序的最后一页是带有浏览按钮的Attachment
页面,该页面呈现AttachmentButton
组件,并向AttachmentButton
组件发送了回调。然后,父页面将带有回调的附件发送到上部App
组件。
所有页面的更改都已在附件状态旁边的上部ticket
状态下正确设置,this.state.ticket.attachment
始终为{}
。
知道我想念什么吗?
附件页面:
export default class Attachment extends React.Component {
handleAddAttachment = file => {
this.props.handleChange('attachment', file);
};
render() {
const { ticket} = this.props;
const { departments, request } = ticket;
return (
<div css={pageWrap}>
<div css={attach}>Upload attachments here</div>
<AttachmentButton handleAddAttachment={this.handleAddAttachment} />
<AttachedFile />
</div>
);
}
}
AttachmentButton组件:
export default function AttachmentButton({ handleAddAttachment }) {
const handleUpload = file => {
handleAddAttachment(file);
};
return (
<div>
<input type="file" css={selectButton} onChange={e => handleUpload(e.target.files[0])} />
Select file
</div>
);
应用程序组件:
export default class App extends React.Component {
state = {
ticket: {
departments: '',
request: '',
exactRequest: '',
attachment: {},
},
};
makeHandleChange = (pageName, change) => {
this.setState({
ticket: { ...this.state.ticket, [pageName]: change },
});
};
render() {
const { ticket } = this.state;
return (
<div>
<Router handleChange={this.makeHandleChange} ticket={ticket} />
<pre>{JSON.stringify(this.state.ticket, null, 2)}</pre>
</div>
);
}
}
最终状态:
{
"departments": {
"catId": 4,
"catName": "Test"
},
"request": {
"subCatId": 9,
"subCatName": "test4"
},
"exactRequest": "12345",
"attachment": {} //always empty
}
答案 0 :(得分:2)
ticket.attachment.file
是一个File对象,它被字符串化为{}
。因此,它仅显示{}
。
console.log(JSON.stringify(new File([], "a"), null, 2))