【问题标题】:Child component not get new props when parent component change state ( Functional Component )父组件更改状态时子组件不会获得新的道具(功能组件)
【发布时间】:2021-01-28 02:22:04
【问题描述】:

为什么当父组件改变状态时我的子组件没有得到新的道具。我使用数据库中包含 3 个元素的列表来测试并在 Add_Friend_Modal 中声明 list_user_selected 以存储所有子 Add_Friend_Selected。我尝试当用户单击 Add_Friend_Modal 中的删除按钮时,状态 list_user_selected 将被更新。但是当我单击第一个子组件的按钮删除时,props.list_user_selected 刚刚得到数组 []。第二个子组件得到数组 [第一个子组件]。第三个子组件得到数组[第一个子组件,第二个子组件]。我已经尝试了一切,但没有奏效。谁能给我解释一下为什么,以及如何解决它

子组件

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>
    )
}

父组件

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)
                })
        }
    }

【问题讨论】:

  • 你的父组件不返回任何东西。您是否在问题中包含了所有代码?
  • 我建议你应该使用骆驼风格的命名约定而不是当前的。 Nhức mắt vãi :)))
  • 存储实例化的反应组件是一种反模式,容易出现陈旧状态/道具外壳的问题。相反,您应该存储可以派生 UI 的状态,即将作为 prop(s) 传递的数据存储到 Add_Friend_Selected 并将 JSX 映射到您的渲染函数返回中。

标签: javascript reactjs react-hooks


【解决方案1】:

修复代码的步骤:

  • 'useEffect'中的钩子不要在'componentDidMount'以外的地方调用api

  • 如果你想使用一个函数来渲染你的组件,你需要在你的函数组件的返回方法中调用它

看看这段代码能不能帮到你:

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

尝试将此代码调整为适合您的代码:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2018-11-03
    • 2021-03-23
    相关资源
    最近更新 更多