首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在地图中包含条件的useState

在地图中包含条件的useState
EN

Stack Overflow用户
提问于 2019-07-02 01:02:34
回答 1查看 68关注 0票数 1

我有以下状态

代码语言:javascript
复制
const [thumbnail, setThumbnail] = useState({
  id: null,
  image: 'https://via.placeholder.com/200x100'
});

我可以在handleChange函数中设置缩略图,如下所示

代码语言:javascript
复制
fetch(`/category/${id}`, {
  method: 'PUT',
  body: formData
})
  .then(res => res.json())
  .then(response =>
    setThumbnail({ id: response.id, image: response.thumbnail })
  );

如何在地图中显示缩略图,如下所示

代码语言:javascript
复制
{data &&
  data.map((category: CategoryInterface) => (
    image={}

<input
  accept="image/*"
  hidden
  ref={ref =>
    (inputRefs[
      category.id
    ] = ref as HTMLInputElement)
  }
  type="file"
  onChange={e => handleChange(e, category.id)}
/>
<IconButton
  onClick={() => handleClick(category.id)}
>

所以基本上我希望默认显示category.thumbnail和占位符,如果它不存在,如果我更改缩略图,它应该只更改我更改的缩略图,但如果我在image={}中设置thumbnail状态,它会将所有缩略图更改为我设置的缩略图,有没有方法只更改特定的缩略图?

EN

回答 1

Stack Overflow用户

发布于 2019-07-02 05:45:23

修复了以下问题

代码语言:javascript
复制
const [data, setData] = useState([] as CategoryInterface[]);
const [loading, setLoading] = useState(false);

useEffect(() => {
  fetch('/categories')
    .then(res => res.json())
    .then(response => setData(response));
}, [loading]);

// This part is called inside a map
setLoading(true);
// fetch
.then(() => setLoading(false));

// This part is inside a map
image={
  data.find(c => c.id === category.id)!.thumbnail ||
  'https://via.placeholder.com/200x100'
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56839617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档