简体   繁体   English

在 function 中使用更新的 state

[英]using updated state in function

I have a function called confirmOrder that takes in orderData and makes an API call with that data:我有一个名为confirmOrder的 function 接收orderData并使用该数据进行 API 调用:

const confirmOrder = () => {
    // updateTime();
    updateDate();
    // delete this
    console.log(`order data: ${JSON.stringify(orderData)}`);
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, orderData)
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}

The orderData object has properties for both date and time : orderData object 具有datetime属性:

const [orderData, setOrderData] = useState({
    date:'',
    time: '',
    truck_id: props.selectedTruck.id,
    breakdown: props.order,
    subtotal: orderSubtotal,
    tip: tipVal.tip,
    total: orderSubtotal + Number(tipVal.tip)
})

As you can see, when I run confirmOrder (through an onClick), a call is made inside that function (ie updateDate ) that should update the values of orderData.date and orderData.time .如您所见,当我运行confirmOrder (通过 onClick)时,会在 function(即updateDate )内部进行调用,该调用应该更新orderData.dateorderData.time的值。 Here is the code for that:这是代码:

    const updateDate = () => {
        let date = new Date();
        let month = date.getMonth() + 1;
        if (month < 10) {
            month = '0' + month;
        };
        let calenDay = date.getDate();
        if (calenDay < 10) {
            calenDay = '0' + calenDay;
          };
        setOrderData({
            ...orderData,
            date: `${date.getFullYear()}-${month}-${calenDay}`,
            time: `${date.getHours()}:${date.getMinutes()}`
        });
    }

The problem I'm having is when I make the API call inside of confirmOrder , orderData.date and orderData.time are being sent to the backend as empty strings instead of with the updated code.我遇到的问题是,当我在 confirmOrder 内部进行confirmOrder调用时, orderData.dateorderData.time将作为空字符串而不是更新的代码发送到后端。 How can I resolve this problem?我该如何解决这个问题?

In React, setting state is asynchronous .在 React 中, 设置 state 是异步的 When you call the state updater, all you do is schedule an update and rerender.当您调用 state 更新程序时,您所做的就是安排更新和重新渲染。 The rest of your function will finish running and then the state will be updated and your component rerendered. function 的 rest 将完成运行,然后state 将被更新并重新渲染您的组件。

If your UI does not depend on the date and time strings, they should not be included in the state at all.如果您的 UI 不依赖于日期和时间字符串,则它们根本不应该包含在 state 中。 You should generate those strings and then combine them with the state to send the request.您应该生成这些字符串,然后将它们与 state 组合以发送请求。

const updateDate = () => {
    let date = new Date();
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    };
    let calenDay = date.getDate();
    if (calenDay < 10) {
        calenDay = '0' + calenDay;
    }
    return ({
        date: `${date.getFullYear()}-${month}-${calenDay}`,
        time: `${date.getHours()}:${date.getMinutes()}`
    });
}

const confirmOrder = () => {
    const date = updateDate();
    axiosWithAuth()
        .post(`/diner/${props.account.id}/confirm-order`, { ...date, ...orderData })
        .then(res => {
            console.log(res);
        })
        .catch(err => console.log(err));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM