Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Set与react';什么是美国?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何使用Set与react';什么是美国?

Javascript 如何使用Set与react';什么是美国?,javascript,reactjs,Javascript,Reactjs,我有一个数组,我必须从中添加/删除元素,我想我应该使用Set来完成这项工作,因为它的add具有和delete const [tags, setTags] = React.useState(new Set()) 如果我想向标记添加一些内容,如何使用设置标记?还是只调用标记.add() ASet根据定义是可变的,如果您仅调用const newSet=Set,React将不会触发新渲染。添加(0)导致上一个与新设置之间的浅层比较将始终断言为true 您可以使用spread操作符在每次更新之间更改引用

我有一个数组,我必须从中添加/删除元素,我想我应该使用
Set
来完成这项工作,因为它的
add
具有
delete

const [tags, setTags] = React.useState(new Set())

如果我想向
标记添加一些内容
,如何使用
设置标记
?还是只调用
标记.add()

A
Set
根据定义是可变的,如果您仅调用
const newSet=Set,React将不会触发新渲染。添加(0)
导致上一个与新设置之间的浅层比较将始终断言为
true

您可以使用
spread
操作符在每次更新之间更改引用,并且仍然保持集合的所有行为

添加元素

const [state, setState] = useState(new Set())

const addFoo = foo =>{
    setState(previousState => new Set([...state, foo]))
}
您仍然可以使用
add
方法,因为它返回更新的集合

const addFoo = foo =>{
    setState(prev => new Set(prev.add(foo)))
}

删除元素

const [state, setState] = useState(new Set())

const addFoo = foo =>{
    setState(previousState => new Set([...state, foo]))
}
删除
有点棘手。首先需要将其转换为一个数组,
过滤
并传播结果

const removeFoo = foo =>{
    setState(prev => new Set([...prev].filter(x => x !== foo)))
}
为了更好地理解上面的代码,您可以像这样拆分它

const removeFoo = foo =>{
    const arr = [...state].filter(x => x !== foo)
    setState(new Set(arr))
}

你必须创建一个新的集合,否则react不会知道它需要重新加载。像下面这样的东西会有用的

setTags(tags => new Set(tags).add(tag))

我遵循了以下方法,并且与我的React本机组件配合得很好


const DummyComponent = () => {
const [stateUserIds, setStateUseIds] = useState(new Set());

....
....

const handleUserSelected = user => {
    // Since we cannot mutate the state value directly better to instantiate new state with the values of the state
    const userIds = new Set(stateUserIds);

    if (userIds.has(user.userId)) {
      userIds.delete(user.userId);
      setStateUseIds(userIds);
    } else {
      userIds.add(user.userId);
      setStateUseIds(userIds);
    }
  };

....
....


return (
   <View> 
       <FlatList
          data={dummyUsers}
          renderItem={({item, index}) => {
            const selected = stateUserIds.has(item.userId);
            return (

                <View style={{flex: 2}}>
                  <Switch
                    isSelected={selected}
                    toggleSwitch={() => handleUserSelected(item)}
                  />
                </View>
            );
          }}
          keyExtractor={(item, index) => item.userId.toString()}
        />
  </View>)

}


常量DummyComponent=()=>{
const[stateUserIds,setStateUseIds]=useState(newset());
....
....
const handleUserSelected=用户=>{
//因为我们不能直接更好地改变状态值,用状态值实例化新状态
const userIds=新集合(stateUserIds);
if(userId.has(user.userId)){
userId.delete(user.userId);
SetStateUseID(用户ID);
}否则{
添加(user.userId);
SetStateUseID(用户ID);
}
};
....
....
返回(
{
const selected=stateUserIds.has(item.userId);
返回(
handleUserSelected(项目)}
/>
);
}}
keyExtractor={(项,索引)=>item.userId.toString()}
/>
)
}
希望这对使用相同用例的人有所帮助。
请参考以下内容,因为集合不是不可变的数据结构,并且React的状态需要不可变。这是否回答了您的问题?谢谢所以,如果每次都要重新创建Set,那么使用Set是个坏主意吗?似乎我也必须克隆一个常规数组,所以我想知道哪个是首选。一个
集合
存储唯一的值,所以除非你想对过滤掉重复值的部分进行编码,否则每次创建一个新的
集合
都可以。谢谢!既然它返回一个布尔值,那么删除呢?对不起,我不太熟悉…更新了答案!