当父组件更改状态时,为什么我的子组件无法获得新的道具。我使用数据库中包含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)
})
}
}
答案 0 :(得分:0)
修复代码的步骤:
如果在“ useEffect”中使用了钩子,请不要在“ componentDidMount”以外的地方调用api
如果要使用函数来渲染组件,则需要在功能组件的return方法中调用它
查看此代码是否可以帮助您:
count2
尝试使此代码适合您的代码:)