简体   繁体   English

如何从 Reactjs 中的 useEffect 钩子访问道具

[英]How to access props from useEffect hook in Reactjs

I am fetching data from a news API and storing it in my state upon completion, then also passing the value of the state as props to a child component.我正在从新闻 API 获取数据并在完成后将其存储在我的状态中,然后还将状态值作为道具传递给子组件。

The data returned by the API is an array of objects. API 返回的数据是一个对象数组。 I only want to pass one element (object) of that array(which is now in my state) to my child component.我只想将该数组(现在处于我的状态)的一个元素(对象)传递给我的子组件。 So, I did just that by using the arrays conventional traversal method ([]) to pass one element, but unfortunately, when I tried using the useEffect hook in my child component to console log the props (which worked ), I was unable to access the properties of my element (object) from neither the hook nor from the body of the component as it kept on telling me that its undefined and that I have to cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.因此,我通过使用数组常规遍历方法 ([]) 传递一个元素来做到这一点,但不幸的是,当我尝试在子组件中使用 useEffect 钩子来控制台记录道具(有效)时,我无法从钩子或组件主体访问我的元素(对象)的属性,因为它一直告诉我它未定义,并且我必须在 useEffect 清理函数中取消所有订阅和异步任务。 So I tried passing that one element as an array using the splice method in order to be traversed from the child component using the map method (which worked), however, I was still unable to access the properties from the useEffect hook.因此,我尝试使用 splice 方法将该元素作为数组传递,以便使用 map 方法(有效)从子组件遍历,但是,我仍然无法从 useEffect 钩子访问属性。

Parent Component (Home.js)父组件 (Home.js)

 ...
const [data, setData]= useState([])
 useEffect(()=>{

        const fetch= async()=>{
            const response= await axios(url)
            const results= response.data
            setData(results.articles.slice(0,5))
        }
        fetch()

    },[url])

return(
    <>
    <Categories onClick={fetchCategory}/>
    <section className={classes.latest}>
    <Vertical postArray={data.slice(0,1)} postObject={data[0]}/>
    </section>
    </>
)
}

export default Home

Child component (Vertical.js)子组件(Vertical.js)

const Vertical=(props)=>{

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

}, )

return(
    <>
    {/* <article key={props.postObject.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{props.postObject.title}</h2>
            <p>{props.postObject.description}</p>

        </div>
    </article> */}
    {props.postArray.map(post=>(
        <article key={post.content} className={classes.article}>
        <figure className={classes.article_figure}>
            <img src='' alt="article alternative"/>
        </figure>
        <div className={classes.article_details}>
            <h2>{post.title}</h2>
            <p>{post.description}</p>

        </div>
    </article>
    ))}
    </>
)
}

export default Vertical

The reason for this is that I need to access an URL which is inside the passed object in order to make another to fetch the thumbnail for that post.这样做的原因是我需要访问传递对象内的 URL,以便让另一个 URL 获取该帖子的缩略图。

you need to give dependencies to the useEffect, for it to watch and console您需要为 useEffect 提供依赖项,以便观察和控制它

useEffect(() => {
    // console.log('postArray',props.postArray.title)
    console.log('postObject',props.postObject.title)

},[props.postObject.title]) //this will ensure that this prop is watched for changes

Edit : for all those with undefined errors you can do the following change in the dependency编辑:对于所有未定义错误的人,您可以在依赖项中进行以下更改

useEffect(() => {
        // console.log('postArray',props.postArray.title)
        console.log('postObject',props?.postObject?.title) // optional-chaining would take care of the undefined check 
    
    },[props?.postObject?.title]) // optional-chaining would take care of the undefined check 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM