javascript - 根据 id 更新对象,错误 'this.props.update' is not a function
问题描述
update
将函数传递给todo
组件时传递给onSave
函数。我保存表格。我调用函数onSave
。得到错误:this.props.update
不是一个函数。
当我点击保存时,它会自动刷新页面。
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>
);
}
}
* * Todo * *
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>
)
}
}
解决方案
您需要在父函数的构造函数中绑定更新函数,以便在子函数中作为对父函数的引用,例如:
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 line right here is the difference
this.update = this.update.bind(this)
}
//blablabla
}
然后当你在子节点中执行 this.props.update() 时,将执行的函数是父节点中的函数,改变父节点状态。
推荐阅读
- sql - 在 SQL Server(或任何 SQL 语言)中,您可以按单词变体分组吗?
- c# - C# | 在应解压缩文件的书面程序中出现错误“找不到路径的一部分”
- c# - 嵌套实用程序类的重用
- javascript - 画布 - 无法读取未定义的属性“x”
- javascript - 在本机反应中制作可重用组件?
- powershell - 将字母数组转换为小写
- dynamic - PowerBI 构建动态图例
- linux - 在 Vim 中编辑 Go 源文件时如何禁用空格突出显示?
- javascript - 通过正则表达式将字符串的开头(空字符串)捕获为匹配本身
- laravel - 清除缓存重定向后的 Laravel 不起作用