反应:页面未重定向,并得到警告:来自useState()和useReducer()的状态更新挂钩不支持第二个回调参数

时间:2019-11-18 13:44:47

标签: reactjs

目标: 我想收取数据条费用,发送电子邮件,清除本地存储中的购物车,然后向用户显示一条成功的消息,然后重定向到主页。一切正常,直到最后一步。显示成功消息后,它不会被重定向。

错误:

  

警告:通过useState()和useReducer()挂钩进行状态更新   不支持第二个回调参数。产生副作用   渲染后,使用useEffect()在组件主体中声明它。

系统:

  • Node.js版本:12.13.0
  • NPM版本:6.12.0
  • Strapi版本:3.0.0-beta.17.4
  • 数据库:MongoDB地图集云
  • 操作系统:LinuxMint 19.2 Cinnamon
  • 前端:React 16.11.0
  • strapi-provider-email-sendgrid“:” ^ 3.0.0-beta.17.5“

代码:

const [cartItems,setCartItems] = useState([])

    useEffect(()=> {
        const items = getCart()
        setCartItems(items)
    }, [])


    const showToast = (toastMsg, redirect = false) => {
        setFormData({...formData, toast: true, toastMsg})
        setTimeout(() => setFormData({...formData, toast: false, toastMsg:''},
        // if true passed to 'redirect' argument, redirect home
         ()=> redirect && props.history.push('/')), 
        5000)
    }

const handleSubmitOrder = async () => {
        const amount = calculateAmount(cartItems)
        setFormData({...formData, orderProcessing: true})

        let token
        try {
            //create stripe token
            //create order with strapi (request to backend)
            //set orderProcessing to false set modal to false
            //clear user cart 
            //show success toast 
            let jwtToken = getToken()
            // console.log(jwtToken)
            const response = await props.stripe.createToken()
            token = response.token.id
            // console.log(token)
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer '+ jwtToken
              }
            await axios
            .post(`${apiUrl}/orders`, {
                amount, 
                productItems: cartItems,
                city,
                zipcode, 
                address,
                token
            }, {headers})
            await axios
            .post(`${apiUrl}/email`, {
                    to: confirmEmail,
                    from: 'hi@anniesveganbakery.com',
                    subject: `Order Confirmation from Annie's Vegan Bakery`,
                    text: 'Your order has been processed.',
                    html: '<h1>Expect your order to arrive in 2-3 shipping days.</h1>'
                }
            ,{headers})
            setFormData({...formData, orderProcessing: false, modal: false})
            clearCart()
            showToast('Your order has been successfully submitted', true)
        } catch (error) {
            //set order processing to false, modal to false
            //show error message in toast
            setFormData({...formData, orderProcessing: false, modal: false})
            showToast(error.message)
        }
    }

问题:是什么导致此问题,如何解决?

1 个答案:

答案 0 :(得分:0)

我这样写解决了这个问题

 const showToast = (toastMsg, redirect = false) => {
        setFormData({...formData, toast: true, toastMsg})
        setTimeout(() => setFormData({...formData, toast: false, toastMsg:''}), 5000)
        // if true passed to 'redirect' argument, redirect home
        setTimeout(() => redirect &&  props.history.push('/'), 6000)
    }

我不确定这是最好的方法,但是现在没有错误,一切都很好。