当我保存表格时。我将函数称为onSave
。网页是自动刷新的
class App extends React.Component {
constructor() {
super();
this.state = {
todos: [{
id: 1,
date: '2019-12-09',
description: 'Hello'
}, {
id: 2,
date: '2019-11-10',
description: 'World'
}],
isEditing: false,
id
};
this.update = this.update.bind(this)
}
update(id, time) {
this.setState({
todos: this.state.todos.map(el => (el.id === id ? Object.assign({}, el, {
time
}) : el))
});
setEditing = (id) => {
this.setState({
isEditing: !this.state.isEditing,
id: id
})
}
render() {
return ( < div >
< ul > {
this.state.todos
.map((todo, index) =>
< Todo key = {
todo.id
}
index = {
index
}
todo = {
todo
}
setEditing = {
this.setEditing
}
update = {
this.update
}
/>
)
} < /ul> < /div>
);
}
}
**待办事项**
class Todo extends Component {
state = {
startDate: new Date(),
description: '',
}
handleChange = (date) => {
this.setState({
startDate: date
});
}
handleDescription = (evt) => {
this.setState({
description: evt.target.value
})
}
saveEdit = () => {
const {
description, status
} = this.state;
this.props.update(this.props.id, {
description,
status,
date: this.state.date
})
}
onSave = () => {
const {
description
} = this.state;
this.props.update(this.props.id, {
description, date: this.formatDate()
});
this.setState({
isEditing: false
})
}
componentDidMount = () => {
const {
todo
} = this.props;
this.setState({
description: todo.description,
startDate: new Date(todo.date)
})
}
render() {
return ( < div > {
this.state.isEditing
? ( < EditForm handleChange = {
this.handleChange
}
description = {
this.state.description
}
startDate = {
this.state.startDate
}
handleDescription = {
this.handleDescription
}
onSave = {
this.onSave
}
onCancel = {
this.onCancel
}
/>): ( < li >
< div > {
this.props.todo.date
} < /div> < div > {
this.props.todo.description
} < /div> < button onClick = {
this.setEditing(this.props.todo.id)
} > Edit < /button> < /li>
)
} < /div>
)
}
}
答案 0 :(得分:1)
尝试使用event.preventDefault()
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
答案 1 :(得分:1)
添加event.preventDefault()应该可以解决问题。
onSave = (event) => {
event.preventDefault();
const {
description
} = this.state;
this.props.update(this.props.id, {
description, date: this.formatDate()
});
this.setState({
isEditing: false
})
}
另外,类似的帖子。
Stop form refreshing page on submit
Automatically refresh the page after saving the edited form in React