简体   繁体   English

当父组件改变状态时,子组件不会获得新的道具(功能组件)

[英]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.我使用数据库中包含 3 个元素的列表来测试和声明 Add_Friend_Modal 中的 list_user_selected 以存储所有子 Add_Friend_Selected。 I trying when user click remove button in Add_Friend_Modal then state list_user_selected will be updated.我尝试当用户单击 Add_Friend_Modal 中的删除按钮时,状态 list_user_selected 将被更新。 But when I click button delete of first child component, props.list_user_selected just got array [].但是当我单击第一个子组件的按钮删除时,props.list_user_selected 刚刚得到数组 []。 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'在'useEffect'中的钩子的情况下,不要在'componentDidMount'以外的地方调用apis

  • 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 :)尝试将此代码调整为您的:)

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

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