简体   繁体   中英

Error when clicking on an element: Objects are not valid as a React child

I use a map with custom markers on the site. 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. Marker coordinates and house information comes from 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. 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]): 在此处输入图像描述

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

Additional info; selectedHouse is empty on the first render

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

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