请问下关于不改变state里面值的问题
来源:3-4 分析State保存位置

hpbrave
2019-03-12
getVisibleTodos = () => {
const currentFilter = this.state.filter;
return this.state.todos.filter(item => {
if(currentFilter === “active”){
return !item.completed
}else if(currentFilter === “completed”){
return item.completed
}else {
return true;
}
})
}
在这个函数中,一开始就把this.state.filter赋值给currentFilter,是怕把state中的值改变了么?但是this.state.filter这个值在这个函数中并没有被改变啊,请问这种情况下也需要把它赋给别的变量,再在函数中使用那个变量么?
非常感谢!
写回答
1回答
-
你好,这里并不是担心state中的值改变。这只是一种变量引用的最佳实践的写法。如果不赋值给currentFilter,filter内需要多次写this.state.filter,比较繁琐,而且变量访问性能上也比直接访问currentFilter要差一些。
00
相似问题