简体   繁体   English

在子组件中记录道具会给出更新的值,而在父组件中定义的 state 本身仍未更新

[英]Logging the Props in child component gives the updated value whereas state itself defined in the parent still not gets updated

I'm a beginner in React and stuck with some problem.我是 React 的初学者,遇到了一些问题。 I have two components.我有两个组件。 one is parent(App.js) which passes its state to child component(CardList).一个是父组件(App.js),它将其 state 传递给子组件(CardList)。 the other is child which receives passed state and use it as props.另一个是接收通过 state 并将其用作道具的孩子。 As I have logged the value of profiles props in CardList it gives the updated value of state that I have defined in the Parent Component(App.js) and whereas state itself defined in the parent still not gets updated.当我在 CardList 中记录了配置文件道具的值时,它给出了我在父组件(App.js)中定义的 state 的更新值,而在父组件中定义的 state 本身仍未更新。 Please refer to the screenshot below:-请参考下面的截图:-

在此处输入图像描述



Parent Component **App.js**
import React, { useState } from 'react';
import Form from './Form';
import CardList from './CardList';

export default function App() {
      const [profiles, setProfiles] = useState([]);
      const addNewProfile=(profile)=>{
      setProfiles([...profiles, profile]);
      console.log(profiles);
  }
  return (
    <>

  <Form addProfile={addNewProfile}/>
  <CardList profilese={profiles}/>
</>
  );
}



Child Component -- **CardList.js**
import React from 'react';
import Cardi from './Cardi';

 export default function CardList(props)
{

   console.log("Everytime State of Parent change");
     return(
      <div>
         {props.profilese.map(profile => <Cardi key={profile.id} profile={profile}/>)}          
     </div>
       );
}



Another Child Component -- **Form.js**
import React,{useState} from 'react';
import axios from 'axios';
import regeneratorRuntime from "regenerator-runtime";

export default function Form(props)
{
    const[username,setUsername]=useState("");

   const handleSubmit=async(event)=>{
         event.preventDefault();
         try{
        const resp= await axios.get
         (`https://api.github.com/users/${username}`);
         const data=await resp.data;
          props.addProfile(data);
         }catch(err)
         {
             console.log("Exception Occured"+ err);
         }
    }
    return(
     <form  onSubmit={handleSubmit}>
        <input type="text"
         value={username}
         onChange={event=>
            {setUsername(event.target.value)}}

         />
         <button >Search</button>
     </form>
    );
}


**Cardi.js**
import React from 'react';


export default function Cardi(props)
{

console.log(props.profile);
if(props.profile===undefined)
{
    return (
       <div>Can't find that username</div>
    );
}
else{
return (


    <>
       <img src={props.profile.avatar_url}/>
       <div className="info">
      <div className="name">{props.profile.name}</div>
      <div className="company">{props.profile.company}</div>
    </div>
    </>

);
}
}

As mentionned in this post , setState is asynchronous.正如这篇文章中提到的,setState 是异步的。 If you want to see the updated state, you should put console.log outside of addNewProfile function:如果您想查看更新的 state,您应该将console.log放在addNewProfile function 之外:

const addNewProfile=(profile)=>{
  setProfiles([...profiles, profile]);
}
console.log(profiles); // this will be called each time state is modified by addNewProfile 

If you want to log profiles only when they are updated, you can do it with useEffect :如果您只想在更新时记录配置文件,您可以使用useEffect来完成:

const addNewProfile=(profile)=>{
  setProfiles([...profiles, profile]);
}
useEffect(() => { console.log(profiles) }, [profiles])

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

相关问题 父组件的 state 更新后,子组件中的道具未更新 - props not updating in child component after parent component's state is updated 道具值没有在vue中将更新的值从父组件发送到子组件 - props value not sending the updated value from parent to child component in vue VueJS-道具不会通过父项的更改在子项中更新 - VueJS - Props are not updated in child component by changes in parent React hook state 在父组件中更新,但子组件没有收到新的道具 - React hook state updated in parent but child component does not receive new props 当父 state 更新时,子道具不会 - When parent state is updated child props won't 将更新的父状态传递给子道具 React.js - Pass updated parent state to child props React.js 发送更新的父 state 时反应子道具不更新 - react child props does not update when sending updated parent state ReactJS更新状态未实时传递给子组件 - ReactJS Updated state not passed in realtime as props to child component reactjs - 为什么通过父道具和组件onChange更新表单值状态? - reactjs - Why have form value state updated through both parent props and component onChange? 从多个子组件更新父组件 state 未考虑更新的 state 值 - Updating Parent component state from multiple child components not taking updated state value into account
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM