请问下关于不改变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回答

艾特老干部

2019-03-13

你好,这里并不是担心state中的值改变。这只是一种变量引用的最佳实践的写法。如果不赋值给currentFilter,filter内需要多次写this.state.filter,比较繁琐,而且变量访问性能上也比直接访问currentFilter要差一些。

0
0

React16+Redux实战企业级大众点评Web App

从架构设计到部署上线,带你学习React技术栈与核心思想

1071 学习 · 306 问题

查看课程