大神帮忙getDerivedStateFromProps造成多次load数据问题

#1

原来使用componentWillReceiveProps时候,外部传入学生id,判断props不同则调用异步this.loadStudent方法更新学生信息,很好用。
自从使用了新的getDerivedStateFromProps后,好像只能在
componentDidUpdate()中调用this.loadStudent,但由于子页面有组件可写从而render信息,这造成loadStudent在componentDidUpdate()中被调用,怎么解决?
大神帮忙

#2

手段判断一下 props 中的属性在前后是否发生了改变?

#3

用 hooks 吧,

function useStudent(){
  const [student, setStudent] = React.useState(null);
  const [error, setError] = React.useState(null)
  const [loading, setLoading] = React.useState(false);
  useEffect(()=> { 
    setLoading(true)
    loadStudent(props.id).then((x)=> {
      setStudent(x)
      setError(null)
       setLoading(false);
    }, (x)=> {
      setError(x);
      setLoading(false);
    })
  }, [props.id]);
  return {loading, error, student}
}
function View(props){
    const { student, error, loading } = useStudent(props);
    if (loading) { return <Loading/> }
    if (error) { return <TextError error={error}/> }
    return <>JSON.stringify(student)</>
}

进化版

function useAjax( fetchBody ){
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null)
  const [loading, setLoading] = React.useState(false);
  useEffect(()=> {
    if (!fetchBody) return;
    let canceled = false;
    setLoading(true)
    fetchBody().then((x)=> {
      if (canceled) return;
      setData(x)
      setError(null)
       setLoading(false);
    }, (x)=> {
      if (canceled) return;
      setError(x);
      setLoading(false);
    })
    return function cancel(){
       canceled = true
    }
  }, [fetchBody]);
  return {loading, error, data}
}

function View({id}){
    const fetchBody = React.useCallback(()=> loadBody(id), [id])
    const { data: student, error, loading } = useAjax(fetchBody);
    if (loading) { return <Loading/> }
    if (error) { return <TextError error={error}/> }
    return <>JSON.stringify(student)</>
}