首页 > 解决方案 > 如何在使用地图功能时更新一个特定元素的状态

问题描述

我需要针对这种情况的解决方案,我将对此进行解释。

设想:

1-我有一张地图,onMoveEnd我更新了位置state

2-我有一个列表,我正在循环使用.map并渲染SampleComponent

3-然后将位置传递给SampleComponent

4-我SampleComponentExpansion Panel里面,我用它来切换扩展面板isExpanded来处理打开和关闭操作;

问题:

每次更新位置时,它都会在SampleComponent我循环的所有内容中更新。但我只需要在SampleComponent其中更新它isExpanded = true,而不是全部更新它。

任何解决方案?

标签: reactjs

解决方案


实际上我UNSAFE_componentWillReceiveProps以前曾经处理过这种情况。

UNSAFE_对我来说看起来很丑所以我这样做:

在我SampleComponent用过的

   const [location, setlocation] = useState({ title: '' });
   useEffect(() => {
        if (props.isExpanded) {
            setlocation(props.location);
        }
    }, [props.location.title]);

首先,我在需要更新位置时听取位置更改,我检查了isExpanded以确保我的面板已打开,然后我应用更改setlocation(props.location)。并将其更改props.location为 local location


推荐阅读