在react中将数据从一个状态传递到另一个状态


const [object, setObject] = useState({
id: null,
created_date: "2021-02-18",
classroom:"",
name: "",
});

我想传递create_date值给另一个状态

const [notify, setNotify] = useState({
id: 5,
created_by: "1",
notification:"object added",
received_date:created_date,
});

这里,我希望created_date值在received_date

您必须使用effect,因为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])

这是你想做的吗?

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

相关内容

最新更新