【问题标题】:Updating useState from props从 props 更新 useState
【发布时间】:2020-02-24 01:05:03
【问题描述】:

使用其他组件的 props 传递的变量来更新组件中的变量的好习惯是什么?在这里,我尝试根据从不同组件传递的“id”显示图像,在该组件中,我捕获了基于 onClick 事件的 id。可悲的是,我的 useState 组件没有 100% 更新。不知何故,可以正确读取正确的索引,但无法正确显示图像。

const SwiperModal = ({ handleClose, show, membersList, curr_idx }) => {
  const showHideClassName = show ? 'modal display-block' : 'modal display-none';
  const idx = parseInt(curr_idx);
  const [index, setIndex] = useState(idx);

  return (
    <div className={showHideClassName}>
      <section className="modal-main">
        <button className="btn__close" onClick={handleClose}>
          close
        </button>
        <Gallery
          index={index}
          //index variable above is responsible for "which image is displayed from the list"
          onRequestChange={i => {
            setIndex(i);
          }}
        >
          {membersList.map((value, index) => (
            <GalleryImage objectFit="contain" src={value.image} key={index} />
          ))}
        </Gallery>
      </section>
    </div>
  );
};

使用从其他组件传递的 props 来更新变量是一种好方法吗?还是有其他想法可以做到这一点?

【问题讨论】:

  • 我看不到您在哪里使用索引来指定图像。

标签: javascript reactjs components react-hooks


【解决方案1】:

你需要一个监听器来监听curr_idx的变化,否则你的状态不会随着道具变化而更新(由onClick引起),你可以通过useEffect hook实现它:

const SwiperModal = ({ handleClose, show, membersList, curr_idx }) => {
  const [index, setIndex] = useState(parseInt(curr_idx));

  useEffect(() => {
    setIndex(parseInt(curr_idx));
  }, [curr_idx]);

  return (...);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 2020-09-30
    • 2021-03-27
    • 1970-01-01
    • 2019-08-11
    • 2021-01-27
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多