Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
882 views
in Technique[技术] by (71.8m points)

next.js - props is undefined when passing from parent to component in next js

I have /pages/profile.js which calls the LovedOne element, passing values from props. Debugging shows that these values are valid when passed

import React from "react";
import LovedOne from "../components/loved_one";

export const Profile = ({ loved_ones }) => {
  const [session, loading] = useSession();
  if (loading) return <div>loading...</div>;
  if (!session) return <div>no session</div>;

  return (
    <Layout>
      {session && (
        <>
          <img src={session.user.image} className="avatar" />
          <h1>{session.user.name}</h1>
        </>
      )}
      {loved_ones.map((loved_one, index) => (
        <LovedOne
          key={index}
          firstname={loved_one.firstname}
          surname={loved_one.surname}
          email={loved_one.email}
        />
      ))}

      <style jsx>{`
        .avatar {
          width: 220px;
          border-radius: 10px;
        }
      `}</style>
    </Layout>
  );
};

However in /components/loved_one.js my props is undefined

import React, { useState, useRef } from "react";

export const LovedOne = ({ props }) => {
  const [setActive, setActiveState] = useState("");
  const [setHeight, setHeightState] = useState("0px");

  const content = useRef();

  function toggleAccordion() {
    setActiveState(setActive === "" ? "active" : "");
    setHeightState(
      setActive === "active" ? "0px" : `${content.current.scrollHeight}px`
    );
  }

  return (
    <div>
      <div className="row">
        <button
          className={`collection-item ${setActive}`}
          onClick={toggleAccordion}
        >
          <i className="fas fa-plus teal-text"></i>
        </button>
        <div className="col s2">
          {props.firstname} {props.surname}
        </div>
        <div className="col s2">{props.email}</div>
      </div>
      <div ref={content} style={{ maxHeight: `${setHeight}` }}>
        <span>some stuff</span>
      </div>
    </div>
  );
};

export default LovedOne;

I've tried passing single variables, and passing the entire loved_ones object. I get the same problem.

Any help much appreciated!

question from:https://stackoverflow.com/questions/65945905/props-is-undefined-when-passing-from-parent-to-component-in-next-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you tried passing props instead of {props} ?

lose brackets, try this way:

export const LovedOne = (props) => {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...