初始化子组件时出错

问题描述 投票:-1回答:1

我对useEffect感到疯狂。我3个月前开始编码,但我并没有真正的经验。

我有一个父组件,该组件使用useEffect初始化数据库中的一些数据,然后将这些数据作为道具传递给子组件,该子组件使用useEffect初始化数据库中的其他数据。无论我如何尝试,都无法使其正常工作。我认为原因是因为在子组件的初始化完成之前会卸载组件。我一直在阅读文档,但无法弄清楚如何解决此问题。

感谢您能帮助我解决问题。

...
import ModelDesigner from './subComponents/ModelDesigner'

const Model = ({ match }) => {
const [model, setModel] = useState({})

const initialize = async (id) => {
  try {
    const res = await axios.get(`/model/${id}`)
    setModel(res.data)
  } catch (err) {
    console.log(err.response.data)
  }
}

const link = match.params.link

useEffect(() => {
  initialize(link)
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return ( 
<ModelDesigner user={model.user} />
)

...
import PropTypes from 'prop-types'

const ModelDesigner = ({ user }) => {
const [profile, setProfile] = useState({})

const loadProfile = async (id) => {
  try {
    const profile = await axios.get(`/profile/id/${id}`)
    setProfile(profile.data)
  } catch (err) {
    console.log(err.response.data)
  }
}

useEffect(() => {
  loadProfile(user)
}, [])

return ( ... )
reactjs use-effect
1个回答
0
投票

我想我知道这里发生了什么。 Model是异步初始化的,因此,在首次呈现时,model变量是一个空对象。

但是,子ModelDesigner立即呈现,并且其useEffect回调在从API加载模型之前运行。因此,它可能在调用/profile/id/undefined而不是使用您想要的配置文件ID。

解决此问题的一种方法是等待呈现子组件,直到完成加载其道具所需的数据为止。对于这个例子,我想这看起来像:

return model.user
  ? <ModelDesigner user={model.user} />
  : <div />

或者,您可以将user添加为useEffect的依赖项,如果为空值,则跳过API调用。这样,它将等待尝试初始化,直到获得所需的ID。

const loadProfile = async (id) => {
  if (!id) {
    return;
  }

  try {
    const profile = await axios.get(`/profile/id/${id}`)
    setProfile(profile.data)
  } catch (err) {
    console.log(err.response.data)
  }
}

useEffect(() => {
  loadProfile(user)
}, [user])
© www.soinside.com 2019 - 2024. All rights reserved.