[英]Error when clicking on an element: Objects are not valid as a React child
I use a map with custom markers on the site.我在网站上使用带有自定义标记的 map。 On the right is a list of houses that match the markers.
右侧是与标记匹配的房屋列表。 I need to implement the following: when clicking on a marker, the house that corresponds to the marker goes to 1st place in the list.
我需要执行以下操作:单击标记时,与标记对应的房子会排在列表的第 1 位。 Marker coordinates and house information comes from Firebase.
标记坐标和房屋信息来自 Firebase。 Now I have implemented the code for this logic, but when I click on the marker, I get an error - Objects are not valid as a React child.
现在我已经实现了这个逻辑的代码,但是当我点击标记时,我得到一个错误——对象作为 React 子级无效。 How can it be solved?
如何解决?
const List = ({ selectedHouse }) => { const [houseTitles, setHouseTitle] = useState([]); useEffect(() => { const q = query(collection(db, "map-markers")); onSnapshot(q, (querySnapshot) => { setHouseTitle( querySnapshot.docs.map((doc) => ({ id: doc.id, data: doc.data(), })) ); }); }, []); return ( <div style={{ width: "50%" }}> {<ListItem title={houseTitles[selectedHouse]} />} {houseTitles.filter((title, index) => index.== selectedHouse),map((title. index) => ( <ListItem key={index} title={title.data;title} /> ))} </div> ); };
console.log(houseTitles[selectedHouse]): console.log(houseTitles[selectedHouse]):
You don't need curly brackets when using components like that;使用这样的组件时不需要大括号;
...
...
return (
<div style={{ width: "50%" }}>
{houseTitles[selectedHouse] && houseTitles[selectedHouse].data ? <ListItem title={houseTitles[selectedHouse].data.title} />:null }
{houseTitles
.filter((title, index) => index !== selectedHouse)
.map((title, index) => (
<ListItem key={index} title={title.data.title} />
))}
</div>
);
...
...
Also, you probably try to print title in ListItem
component yet you pass the whole object for the selectedHouse此外,您可能尝试在
ListItem
组件中打印标题,但您将整个 object 传递给 selectedHouse
Additional info;附加信息; selectedHouse is empty on the first render
selectedHouse 在第一次渲染时为空
Try this:尝试这个:
const List = ({ selectedHouse }) => {
const [houseTitles, setHouseTitle] = useState([]);
useEffect(() => {
const q = query(collection(db, "map-markers"));
onSnapshot(q, (querySnapshot) => {
setHouseTitle(
querySnapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
);
});
}, []);
return (
<div style={{ width: "50%" }}>
<ListItem title={houseTitles[selectedHouse]?.data?.title} />
{houseTitles
?.filter((title, index) => index !== selectedHouse)
?.map((title, index) => (
<ListItem key={index} title={title?.data?.title} />
))}
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.