[英]Passing data from one state to another state in react
const [object, setObject] = useState({
id: null,
created_date: "2021-02-18",
classroom:"",
name: "",
});
i want to pass the create_date value to anther state我想将 create_date 值传递给另一个 state
const [notify, setNotify] = useState({
id: 5,
created_by: "1",
notification:"object added",
received_date:created_date,
});
here, i want that created_date value in received_date在这里,我想要接收日期中的 created_date 值
You would have to useEffect for that since object
will mutate over time, and notify
has to keep up with that.您必须为此使用 useEffect ,因为object
会随着时间的推移而发生变异,并且notify
必须跟上。
const initialObject = {
id: null,
created_date: "2021-02-18",
classroom:"",
name: "",
}
const [object, setObject] = useState(initialObject);
const [notify, setNotify] = useState({
id: 5,
created_by: "1",
notification:"object added",
received_date:initialObject.created_date,
});
useEffect(()=>{
setNotify(notify => ({...notify, received_date: object.created_date})
}, [object])
Is this what you wanted to do the reference这是你想做的参考
import { useState } from "react";
export default function App() {
const [object, setObject] = useState({
id: null,
created_date: "2021-02-18",
classroom: "",
name: ""
});
const [notify, setNotify] = useState({
id: 5,
created_by: "1",
notification: "object added",
received_date: object.created_date
});
return <div>{notify.received_date}</div>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.