0

Cannot read property 'date' of undefined当我调用我的函数时,我不断收到getDataPrevDay,但console.log(appointment[0].apps.date)记录了正确的日期

const admin = ({data}) => {

const [appointment, setAppointment] = useState(data);

console.log(appointment[0].apps.date)

const getDataPrevDay = async () => {
    let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
    let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
    const res = await fetch(`http://localhost:3000/api/appointmentsdb? 
    date=${newDate}`)
    let json = await res.json();

    setAppointment(json);
}

....

return (
  <button onClick={getDataPrevDay}> Prev Day </button>
 )
}

export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))

return {
    props: {
        data: json
    },
};}

这是处理程序

handler.get(async (req, res) => {
const {date, first_name, last_name, number, email, time} = 
req.query;
const dataModel = 
  {'_id': new ObjectID(), 
  'first_name': first_name,
  'last_name': last_name,
  'number': number,
  'email': email,
  'date': date,
  'time': time
  };

let doc = {}

if(date) {
  doc = await req.db.collection('Info').find({date: date}, 
 {projection : {_id: 0}}).toArray()
} else {
  doc = await req.db.collection('Info').findOne()
} if(doc == null) {
  doc = dataModel;
} 
 res.json(doc);
});
4

1 回答 1

0

道具是动态渲染和更新的。如果它们为空,您可以通过跳过来添加故障安全以避免可统一的值。

const admin = ({data}) => {

const [appointment, setAppointment] = useState(data);

console.log(appointment[0].apps.date)

const getDataPrevDay = async () => {
    if(appointment && appointment.length && appointment[0].apps && appointment[0].apps.date) {
        let currentDate = dayjs(appointment[0].apps.date).format('YYYY-MM-DD')
        let newDate = dayjs(currentDate).subtract(1, 'day').format('YYYY-MM-DD')
        const res = await fetch(`http://localhost:3000/api/appointmentsdb? 
    date=${newDate}`)
        let json = await res.json();

        setAppointment(json);
    }
}

....

return (
  <button onClick={getDataPrevDay}> Prev Day </button>
 )
}

export async function getServerSideProps(context){
const currentDate = dayjs().format('YYYY-MM-DD')
const res = await fetch(`http://localhost:3000/api/appointmentsdb?date=${currentDate}`)
let json = await res.json();
json = json.map(apps => ({apps}))

return {
    props: {
        data: json
    },
};}
于 2021-06-23T07:29:42.243 回答