繁体   English   中英

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

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

我是 React 的初学者,遇到了一些问题。 我有两个组件。 一个是父组件(App.js),它将其 state 传递给子组件(CardList)。 另一个是接收通过 state 并将其用作道具的孩子。 当我在 CardList 中记录了配置文件道具的值时,它给出了我在父组件(App.js)中定义的 state 的更新值,而在父组件中定义的 state 本身仍未更新。 请参考下面的截图:-

在此处输入图像描述



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>
    </>

);
}
}

正如这篇文章中提到的,setState 是异步的。 如果您想查看更新的 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 

如果您只想在更新时记录配置文件,您可以使用useEffect来完成:

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

暂无
暂无

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

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