首页 > 解决方案 > 反应:道具在第一次渲染时有一个值,然后是未定义的

问题描述

export const Modal = (props, { farm, id }) => {
  const [currentUser, setCurrentUser] = useState();

  console.log("NewId", props.id);

  const initialFieldValues = {
    title: "",
    image: "",
    product: "",
    content: "",
    phone: "",
    email: "",
  };

  const [values, setValues] = useState(initialFieldValues);

  function handleChange(e) {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  }

  const handleFormSubmit = (e) => {
    e.preventDefault();
    const obj = {
      ...values,
    };
    getFirebase()
      .database()
      .ref(`Users/${props.id}`)
      // .ref(`Users/${newId}`)

      .push(obj, (err) => {
        if (err) console.log(err);
        // console.log("ID", newId);
      });
  };

父组件

const App = (props) => {
  const [currentUser, setCurrentUser] = useState();
  const [id, setId] = useState("");

useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(async (userAuth) => {
      if (userAuth) {
        const userRef = await createUserProfileDocument(userAuth);
        userRef.on("value", (snapShot) => {
          setCurrentUser({ key: snapShot.key, ...snapShot.val() });
        });
        // }
      }
      if (setCurrentUser(userAuth)) {
      } else if (!userAuth && typeof window !== "undefined") {
        return null;
      }
      const id = userAuth.uid;
      setId(id);
    });
  <>
      <Modal id={id} />
    </>;
    return unsubscribe;
  }, []);

当我在这里 console.log .ref( Users/${props.id}) 它是未定义的。

这是我的控制台的样子:

12modal.jsx:12 'NewId' fRHyyzzEotPpIGUkkqJkKQnrTOF2

12modal.jsx:12 'NewId' 未定义

它带有ID一次和12次undifiend。任何建议将不胜感激。

标签: reactjsreact-props

解决方案


首先,您不能更改道具值,如果 props.id 是一个状态(即const [id, setId] = React.useState(initial value)),那么您只能通过子级未收到的 setId 更改 id,因此我认为父母可能会导致此问题。


推荐阅读