下面的简单钩子组件,提交表单时抛出异常并且useEffect钩子触发并提示错误信息,
如果由于某种原因再次提交 useEffect 不会触发..
我可以向您保证提交,操作按预期进行,因为我跟进了调试器的步骤.. 首次提交后不会进入useEffect..
组件:
minus
动作:
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
const { messages, error } = useSelector((state) => state.contact)
const dispatch = useDispatch()
useEffect(() => {
debugger
if (error) {
alert(messages)
}
}, [error, messages])
const onSubmitForm = (data) => {
dispatch(postContact(data))
}
减速器:
export const postContact = ({ name, email, website, message }) => async (
dispatch
) => {
try {
dispatch({
type: CONTACT_POST,
})
const response = await axios.post('/contact', {
data: {
Name: name,
Email: email,
Website: website,
Message: message,
},
})
dispatch({
type: CONTACT_POST_SUCCESS,
payload: response.data,
})
} catch (error) {
debugger
dispatch({
type: CONTACT_POST_FAIL,
error: error.message,
})
}
}
答案 0 :(得分:1)
因为错误和消息属性的值没有变化。错误值始终分配为“true”。尝试聆听整个状态本身。
const contactState = useSelector((state) => state.contact)
useEffect(() => {
debugger
if (error) {
alert(messages)
}
}, [contactState ])
或者您需要在发布请求时重置错误值和消息
case CONTACT_POST:
return {
...state, error:false, messages:""
}