使用子组件中的异步请求更新父组件状态

I'm using React hooks + Apollo hooks to lazy load a series of components. These components make a query each time they are mounted. I want the parent component for these components to keep track of when each async call resolves with data.

我有一个工作示例,它将父状态传递给它的子状态,并在回调中进行更新。但是,我看到过这样的情况:子级在父级有时间更新之前试图更新父级状态。这导致状态要么更新得过多,要么更新不足。

这是我目前正在做的一个例子:


const Parent = () => {
  const [state, setState] = useState();

  const handleChange = () => {
    setState(state + 1); 
  }

  if (state < 10) {
    return <div>no more results</div>;
  }

  // it's possilbe that 5-6 mount at once and fire off queries
  return (
    <>
      {arr.map(c => <Child handleChange={handleChange} />)}
    </>
  )
}

const Child = ({ handleChange }) => {
  const [ loadMore, { called, loading, data }] = useLazyQuery(QUERY, {
    onCompleted: (data) => {
      if (data.length > 0) {
        handleChange() 
      }
    }
  });

  // When a user scrolls into view, make request
  return (
    <Waypoint onEnter={loadMore}>
      {do something with data}
    </Waypoint>
  )
};

当子级进行异步调用时,是否有更好的方法来管理父级状态?不引入Redux?

评论
  • vgybhu
    vgybhu 回复

    这可能是一个解决方案。

    const Parent = () => {
      const [state, setState] = useState(0);
    
      const handleChange = (idx) => {
        setState(idx); 
      }
    
      if (state < arr.length) {
        return <div>no more results</div>;
      }
    
      return (
        <>
          {arr.map((c, idx) => <Child handleChange={handleChange} key={idx} id={idx}/>)}
        </>
      )
    }
    
    const Child = ({ handleChange, id }) => {
      const [ loadMore, { called, loading, data }] = useLazyQuery(QUERY, {
        onCompleted: (data) => {
          if (data.length > 0) {
            handleChange(id) 
          }
        }
      });
    
      // When a user scrolls into view, make request
      return (
        <Waypoint onEnter={loadMore}>
          {do something with data}
        </Waypoint>
      )
    };