React:将状态设置为es6 Map [英] React: Setting state to an es6 Map

查看:169
本文介绍了React:将状态设置为es6 Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更多是一个通用的最佳实践问题。

This is more of a general, best-practices question.

我一直在使用JavaScript Map在这里和那里玩耍,并一直在尝试查找更多信息。关于将状态属性设置为Map是否被视为反模式/代码异味。下面的链接是Redux存储库中的问题线程,带有一些注释,例如:

I've been playing around here and there with JavaScript Maps and have been trying to find more info on whether or not it's considered an anti-pattern/code smell to set state properties to a Map. The link below is an issue thread in the Redux repo with some comments such as:

您可以将Maps和Sets用作状态值,但是不建议这样做

不过,该主题与Redux有关。那么香草反应呢?任何人都有强烈的意见或见识?抱歉,如果这个问题在错误的位置。

However this thread is about Redux. What about vanilla React? Anyone have any strong opinions or insight? Sorry if this question is in the wrong place.

https://github.com/reduxjs/redux/issues/1499

推荐答案

反应状态应为不可变,因为React使用浅表比较来检查是否相等。比较标量值(数字,字符串)时,它会比较它们的值。比较对象时,它不比较它们的属性-仅比较它们的引用(例如它们指向同一个对象吗?。)。

React state should be immutable because React uses shallow compare to check for equality. When comparing scalar values (numbers, strings) it compares their values. When comparing objects, it does not compare their properties - only their references are compared (e.g. "do they point to same object?).

ES6映射不是不可变的,并且针对可变性进行了优化,因此不建议这样做可以直接在React中使用它们。React将不知道地图是否已更新。

ES6 Maps are not immutable and are optimized for mutability that's why its not recommended to use these in React as it is. React will not know whether map is updated or not.

var map1 = new Map();
var map2 = map1.set('b', 2); // mutate map
map1 === map2; // true because reference remain unchanged after mutation

您可以根据需要使用地图,但需要使用一些不可变性助手,例如 Immutable.js 。以下示例使用了不可变地图

You can use Maps if you want but you need to use some immutability helper e.g. Immutable.js. Following example is using immutable map

const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 2); // Set to same value
map1 === map2; // true
const map3 = map1.set('b', 4); // Set to different value
map1 === map3; // false

参考文献:

https://github.com/reduxjs/redux/ issue / 1499#issuecomment-194002599
https://stackoverflow.com/a/36084891/2073920 a>

这篇关于React:将状态设置为es6 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆