javascript - 我需要使用什么生命周期钩子?- 反应
问题描述
情况是这样的:我有一个数据库,数据在哪里。数据由一组对象构成。这些对象具有三个属性(现在相关)。它们是:id、parentId 和状态。组件使用这些属性构建,并且组件递归地克隆自身,因此它们相互嵌套。它看起来像这样:
class Task extends React.Component{
constructor(props){
super(props);
this.state = {
status: this.props.status
}
}
//gets fired right after the state changed by removeTask
static getDerivedStateFromProps(props){
console.log("state from props")
return{status: props.status}
}
componentDidUpdate(){
console.log("update");
this.checkDeleted()
}
checkDeleted = () => {
if (this.state.status === 'deleted'){
deleteTask(this.props.id) //a function which deletes from database
}
}
tasks = () => {
console.log("childs rendered")
return this.props.tasks
.filter(task => task.pId === this.props.id)
.map(task => {
return <Task
id={task.id}
pId={task.pId}
status={this.state.status}
/>
})
}
removeTask = () => {
console.log("state changed")
this.setState({status: 'deleted'})
}
render(){
console.log("render")
return(
<div
<button onClick={this.removeTask} />
{this.tasks()}
</div>
)
}
}
会发生什么:日志的顺序如下:
- 状态改变(removeTask())
- 来自道具的状态(gDSFP())
- 使成为
- 渲染的孩子(任务()在渲染()内触发)
- 更新 (componentDidUpdate())
这不好,因为当状态从 removeTask() 更改时,它会在组件可以将更改后的状态传递给它的子组件之前使用 gDSFP 从道具中立即返回。但我想从道具设置状态,因为孩子们需要得到它。这里可能发生的情况是: removeTask() 被触发,设置新状态,重新渲染,子节点作为道具获得新状态,当更新发生时,删除所有组件,它是数据库中的子节点。那么什么是好的:
- 点击发生,设置新状态
- 使成为
- 渲染孩子,将他们的状态道具设置为状态
- 检查状态是否为“已删除”
- 如果它被改变,从 props 设置状态,然后重新渲染
这个怎么赚?
解决方案
一开始我对你的订单有疑问。您的数据取决于数据库中的内容。您可能会从状态中删除并且数据库任务失败。那么为什么还要手动更新状态。只需聆听并从来自 DB 的道具中加载您的状态。当您从数据库中删除时,您的道具将被更新并重新渲染。所以基本上如果我是你,我会坚持
class Task extends React.Component{
constructor(props){
super(props);
}
//gets fired right after the state changed by removeTask
static getDerivedStateFromProps(props){
console.log("state from props")
return{status: props.status}
}
componentDidUpdate(){
console.log("update");
}
tasks = () => {
console.log("childs rendered")
return this.props.tasks
.filter(task => task.pId === this.props.id)
.map(task => {
return <Task
id={task.id}
pId={task.pId}
status={this.props.status}
/>
})
}
removeTask = () => {
console.log("state changed");
deleteTask(this.props.id) //a function which deletes from database
}
render(){
console.log("render")
return(
<div
<button onClick={this.removeTask} />
{this.tasks()}
</div>
)
}
}
从上面,您可以注意到我已删除checkDeleted
,因为我不需要更新我的状态。我只能依靠道具。删除设置状态状态,因为我可以只依赖 btw 计数或与 DB 同步的道具状态。
推荐阅读
- asp.net-core - 从 ASP.NET Core 2.2 更新 SQL Server 中的上下文
- c++ - 英特尔引脚:INS_MemoryDisplacement(ins) 并非在所有情况下都有效
- python - 列表比较元素的python列表
- amazon-web-services - 关于为应用程序创建 SAM 模板的建议?
- php - 必须是有效的 JSON 字符串 Laravel 和 Postman
- php - 在没有 JS 的情况下使用 POST 或 GET 循环在 PHP 中从更多输入标签发布数据
- youtube-data-api - 为什么品牌帐户出现以下错误:经过身份验证的用户没有上传和设置自定义视频缩略图的权限
- r - 循环将代码应用于不同的数据并将图保存在 R 中
- javascript - Hot 用 html 和 css 动态创建列表
- r - 为什么summary_table函数在markdown中产生一个不同的表,当它被编织为HTML时