javascript - 使用最初 undefined variable 的属性来实现 useEffect 依赖

标签 javascript node.js reactjs npm

TL;DR: Want to use listRef.current.clientWidth for useEffect dependency.

我想制作一个列表,它会根据列表的宽度自动调整其项目的宽度。我已经很接近了,但我无法检测到 listRef.current.clientWidth 的变化这是 <div className="dynamic-list">的宽度。第一次运行时 listRef 为空,所以我不能有 listRef.current.clientWidth对于 useEffect 依赖项。 listRef ? listRef.current.clientWidth : null对于依赖关系也不适用于 use simple dependency warning

const DynamicList = ({
  dataSource, renderItem, itemMaxWidth, itemHeight,
  margin, height = 500, width = 700 }) => {
  const windowWidth = useWindowDimensions().width; 
  const [itemStyle, setItemStyle] = useState({ width: itemMaxWidth, height: itemHeight });
  const [currentWidth, setCurrentWidth] = useState(null);
  const listRef = useRef();


  useEffect(() => {
    if (listRef) {
      const num = Math.floor(listRef.current.clientWidth / itemMaxWidth)
      console.log(
        num,
        listRef.current.clientWidth,
        listRef.current
      )
      setItemStyle((pre) => ({
        ...pre,
        height: itemHeight,
        margin: margin,
        width: (listRef.current.clientWidth / num) - (margin ? margin * 2 : 0),
      }))
    }

  }, [listRef, windowWidth, itemMaxWidth, margin, itemHeight, width])

  return (
    <div
      className="dynamic-list"
      ref={listRef}
      style={{
        width: width,
        height: height
      }}
    >
      {
        dataSource.map((item, index) => {
          return (
            <div style={itemStyle} key={index}>
              {renderItem(item, index)}
            </div>
          )
        })
      }
    </div>
  );
};

export default DynamicList;
  • 如果有任何能让这一切变得更好的建议,我们将不胜感激。

最佳答案

使用像@TopW3所说的回调引用,我能够解决这个问题。但并不完全满意。 Article that also helped me solve the problem

const DynamicList = ({
  dataSource, renderItem, itemMaxWidth, itemHeight,
  margin, height = 500, width = 700 }) => {
  const windowWidth = useWindowDimensions().width; // 윈도우 크기 변화 감지용
  const [itemStyle, setItemStyle] = useState({
    width: itemMaxWidth,
    height: itemHeight,
    margin: margin
  });
  const [listWidth, setListWidth] = useState(null);

  const onListRefSet = useCallback((ref) => {
    if (ref)
      if (ref.current)
        setListWidth(ref.current.clientWidth);
  })

  useEffect(() => {
    if (listWidth) {
      const num = Math.floor(listWidth / itemMaxWidth);
      setItemStyle((pre) => ({
        ...pre,
        width: (listWidth / num) - (margin ? margin * 2 : 0),
      }))
    }
  }, [listWidth, itemMaxWidth, margin, itemHeight, windowWidth])

  return (
    <div
      className="dynamic-list"
      ref={onListRefSet}
      style={{
        width: width,
        height: height,
        minWidth: itemMaxWidth
      }}
    >
      {
        dataSource.map((item, index) => {
          return (
            <div style={itemStyle} key={index}>
              {renderItem(item, index)}
            </div>
          )
        })
      }
    </div>
  );
};

export default DynamicList;

关于javascript - 使用最初 undefined variable 的属性来实现 useEffect 依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59780409/

相关文章:

reactjs - Nextjs 11 新使用 import 关键字 for image 'src' 抛出错误 CompileError : mutable globals cannot be exported

javascript - getBoundingClientRect() 不一致

javascript - 当主 url 没有改变但表格内容改变时解析网页

node.js - MongoDB - 在 node.js 中使用多个 $elemMatch 运算符更新多个级别的子文档

node.js - 无法在 Linux 上安装 @angular/cli

node.js - 使用 Protractor 作为库时“没有期望的方法”

javascript - Webpack 中 Webpack-Manifest-Plugin 的用途

javascript - 通过 ajax 调用请求页面时,Google 图表未加载

javascript - 将 Prop 传递给 map 中的温度文字

javascript - 当在 ReactJs React-Redux 中仅创建或更新列表中的一个项目时,如何停止重新渲染整个项目列表?