简体   繁体   中英

Child component not get new props when parent component change state ( Functional Component )

Why my child component not get new props when parent component change state. I use a list with 3 element in database to test and state list_user_selected in Add_Friend_Modal to store all child Add_Friend_Selected. I trying when user click remove button in Add_Friend_Modal then state list_user_selected will be updated. But when I click button delete of first child component, props.list_user_selected just got array []. Second child component got array [First Child Component]. Third child component got array [First Child component,Second Child Component]. I have tried everything but it did not work. Can anyone explain to me why, and how to fix it

Child Component

const Add_Friend_Selected = props => {
    return (
        <li className="list-group-item px-0 d-flex">
            <figure className="avatar mr-3">
                <img src={props.avatar} className="rounded-circle" alt="image" />
            </figure>
            <div>
                <div>{props.name}</div>
                <div className="small text-muted">{props.mobile}</div>
            </div>
            <a onClick={() => props.delete_user_selected(props.id)} className="text-danger ml-auto" data-toggle="tooltip" title="Remove">
                <i className="mdi mdi-delete-outline"></i>
            </a>
        </li>
    )
}

Parent Component

const Add_Friend_Modal = props => {
    const [count_user_selected,set_count_user_selected] = useState(0);
    const [list_user_selected,set_list_user_selected] = useState([]);
    const user = useSelector((state) => state.user);
    const input_mobile_friend = useRef("");
    
    const delete_user_selected = (id) => {
        const delete_user_index = list_user_selected.findIndex(user_selected => user_selected.props.id === id);
        console.log(delete_user_index)
        set_list_user_selected([...list_user_selected.splice(delete_user_index,1)])
    }
    const add_invite_friend = () => {
        if(input_mobile_friend.current.value) {
            call_api({
                url : `/users/search?mobile=${input_mobile_friend.current.value}`
            })
                .then(response => {
                    const user_find = response.data.data;
                    if(user_find && !list_user_selected.some(user_selected => user_selected.props.id === user_find._id )) {
                        const new_user_selected = (
                            <Add_Friend_Selected name={user_find.name} avatar={user_find.avatar} 
                                                 mobile={user_find.mobile} id={user_find._id} 
                                                 list_user_selected={list_user_selected}
                                                 delete_user_selected={(id) => {
                                                     delete_user_selected(id)
                                                     set_count_user_selected(list_user_selected.length + 1)
                                                 }}
                                                 />
                        )

                        set_list_user_selected([...list_user_selected,new_user_selected])
                        set_count_user_selected(list_user_selected.length + 1)
                    }
                    else {
                        console.log("Not found")
                    }
                })
                .catch(error => {
                    console.log(error)
                })
        }
    }

Steps to fixing your code:

  • Dont call apis in a place other than 'componentDidMount' in the case of hooks in 'useEffect'

  • If you want to use a function for render your component you need to call it in the return method of your functional component

Look if this code can help you:

//state for update when your api call finished
const [user_find, set_user_find] = useState(null)

//useEffect for call your api
useEffect(() => {
  //componentSkillMount its a variable for not update an unmounted component
  let componentSkillMount = true;
  call_api({
    url : `/users/search?mobile=${input_mobile_friend.current.value}`
    })
    .then(response => {
      //if your component skill mounted you can update that
      componentSkillMount && set_user_find(response.data.data)
    })
  return () => componentSkillMount = false
}, [])

return (
  //if the api call finished you can return a full component
  user_find && (
    <Add_Friend_Selected name={user_find.name} avatar={user_find.avatar} 
      mobile={user_find.mobile} id={user_find._id} 
      list_user_selected={list_user_selected}
      delete_user_selected={(id) => {
          delete_user_selected(id)
          set_count_user_selected(list_user_selected.length + 1)
      }}
      />
  )
)

Try to adapt this code to yours :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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