reactjs - 反应:道具在第一次渲染时有一个值,然后是未定义的
问题描述
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。任何建议将不胜感激。
解决方案
首先,您不能更改道具值,如果 props.id 是一个状态(即const [id, setId] = React.useState(initial value)
),那么您只能通过子级未收到的 setId 更改 id,因此我认为父母可能会导致此问题。
推荐阅读
- sql - 如何在 TSQL 中使用 case 子句在 ROW_NUMBER() OVER 中添加多个排序列
- excel - 在通过powershell完全刷新之前保持excel打开?
- c# - 如何查询所有 Azure 编排实例以确定状态以进行监控?
- javascript - 使用 scrollmagic JS 检测滚动方向
- jquery - 如何在 mvc 项目中设置路由以正常工作?
- python - 如何将 sqlite3 表的变量(其值使用组合框获取)与 pyqt5 中的变量(再次使用组合框获取值)进行比较?
- react-native - 反应上下文未定义
- dictionary - 将 mapAsync 提取到 AkkaStreams 中的方法
- matlab - WORHP - Matlab 界面,LEQSOL 中的错误:符号步骤
- javascript - 如何在Javascript中动态更新对象?