我正在尝试创建一个空的object
。
首先,每个字段都有一个带有空值的名称。一切正常,但格式化name field
这是我的代码:
@observable member = {
//This name field doesn't work
[{name:''}] :
{
age: '',
email: '',
job:'',
info: [
{
email: '',
phone:'',
address: ''
}
],
}
}
当我console.log(member)
时,我得到了:
[object Object]: {dots: "", selected: "", day: "", task: Array(1), name: ""}
我想获得[object Object]
而不是name:''
吗?
答案 0 :(得分:1)
对象以名称:值对的形式编写,您的对象没有正确的密钥class Post extends React.Component<IProps, IState> {
constructor(props: Readonly<IProps>) {
super(props);
this.state = {
id: -1,
title: "",
body: "",
author: "",
date: "",
showDate: true,
editEnabled: false,
showProgressBar: false,
edit: {
title: "",
}
};
}
componentDidMount = () => {
this.setState({
id: this.props['id'],
title: this.props['title'],
body: this.props['body'],
author: "",//this.props['author'],
date: this.convertToReadableDate(this.props['date']),
showDate: !!this.props['showDate'],
})
tinymce.init({
selector: "#edit_body_" + this.props['id'],
skin_url: '/lib/tinymce/skins/ui/oxide',
})
}
convertToReadableDate(unix_timestamp: number): string {
var date = new Date(unix_timestamp * 1000);
return date.toISOString().split("T")[0];
}
handleDelete = () => {
if (confirm("Are you sure you would like to delete this post?")) {
var req = new HTTPRequest("DELETE", "/qa/posts/" + this.state.id);
req.execVoid(HTTP.RESPONSE.OK)
.then(function () {
this.props.deletePost();
M.toast({ html: "Your post was deleted!", classes: "green" })
}.bind(this))
.catch(function (err: Error) {
M.toast({
html: "We have trouble deleting your post. Try again later",
classes: "red"
});
console.error(err.message);
}.bind(this))
}
}
promptSaveChange = () => {
if (this.state.title != this.state.edit.title || tinymce.get('edit_body_' + this.props.id).getContent() !== this.state.body) {
return confirm("You have unsaved changes. Are you sure you would like to proceed?")
} else {
return true;
}
}
handleEdit = () => {
if (this.state.editEnabled) {
if (this.promptSaveChange()) {
this.disableEdit();
}
} else {
this.enableEdit();
tinymce.get('edit_body_' + this.props.id).setContent(this.state.body);
}
}
resetChanges = () => {
this.setState({
edit: {
title: this.state.title
}
})
tinymce.get('edit_body_' + this.props.id).setContent(this.state.body);
}
handleEditSave = () => {
this.showProgress();
var req = new HTTPRequest("PATCH", "/qa/posts/" + this.state.id);
var body_content = tinymce.get('edit_body_' + this.props.id).getContent();
req.execAsJSON({
title: this.state.edit.title,
body: body_content
}, HTTP.RESPONSE.ACCEPTED).then(function (ret) {
this.setState({
title: this.state.edit.title,
body: body_content
});
this.disableEdit();
M.toast({
html: ret['msg'],
classes: 'green'
})
}.bind(this)).catch(function (err: Error) {
console.log(err.message);
M.toast({
html: "We had trouble updating the post. Try again later."
})
}.bind(this)).finally(function () {
this.hideProgress();
})
}
handleTitleEdit = (e) => {
this.setState({
edit: {
title: e.target.value
}
})
}
enableEdit = () => {
this.setState({
editEnabled: true,
edit: {
title: this.state.title
}
}, function () {
M.AutoInit();
})
}
disableEdit = () => {
console.log('disabled: ' + this.state.title);
this.setState({
editEnabled: false
})
}
showProgress = () => {
this.setState({
showProgressBar: true
})
}
hideProgress = () => {
this.setState({
showProgressBar: false
})
}
content = () => {
return (
<div>
<div style={{ display: this.state.editEnabled ? 'none' : null }}>
<span className="card-title">{this.state.title}</span>
<div dangerouslySetInnerHTML={{ __html: this.state.body }}></div>
<small> {this.state.showDate ? "Posted at: " + this.state.date : ""}</small>
</div>
<div style={{ display: this.state.editEnabled ? null : 'none' }}>
<input type="text" name="title" value={this.state.edit.title} placeholder={this.state.title} onChange={this.handleTitleEdit} />
<textarea id={"edit_body_" + this.props.id}></textarea>
</div>
</div>
)
}
actions = () => {
return (
<>
<div className="row" style={{ display: this.state.editEnabled ? null : 'none' }}>
<a className="btn-small green waves-effect" onClick={this.handleEditSave}><i className="material-icons left">save</i> Save</a>
<a className='dropdown-trigger btn-flat blue-text' href='#' data-target='edit-options'>More</a>
<ul id='edit-options' className='dropdown-content'>
<li>
<a href="#!" className="orange-text" onClick={this.resetChanges}>Reset Changes</a>
</li>
<li>
<a href="#!" className="orange-text" onClick={this.handleEdit}>Cancel</a>
</li>
<li>
<a href="#!" className="red-text" onClick={this.handleDelete}>Delete</a>
</li>
</ul>
<div className="progress" style={{ display: this.state.showProgressBar ? null : "none" }}>
<div className="indeterminate"></div>
</div>
</div>
<div className="row" style={{ display: this.state.editEnabled ? 'none' : null }}>
<a className="btn-small orange waves-effect" onClick={this.handleEdit}><i className="material-icons left">edit</i> Edit</a>
</div>
</>
)
}
render(): React.ReactNode {
return (
<div className="card">
<div className="card-content">
{this.content()}
</div>
<div className="card-action">
{this.actions()}
</div>
</div>
)
}
}
export default Post;
。您可以执行以下操作以正确格式化对象。
[{name: ''}]
或
@observable member = {
// will store names in array
// or just do
// name: '',
name: '',
age: '',
email: '',
job:'',
info: [
{
email: '',
phone:'',
address: ''
}
],
}
然后访问值,例如
@observable member = {
names : [{'name': ''}],
memberInfo: {
age: '',
email: '',
job:'',
info: [
{
email: '',
phone:'',
address: ''
}
],
}
}
答案 1 :(得分:0)
您可以使用JSON.Stringify()将Javascript对象转换为JSON。
console.log(JSON.Stringify(member).name)
应该做这项工作。