下面的示例钩子组件,提交表单时抛出异常和useEffect钩子触发并提示错误消息fine,
如果出于某种原因再次提交useEffect不会触发。。
我可以向你保证,由于我与调试器一起跟进步骤,操作如预期。。它在第一次提交后不会进入useEffect。。
组件:
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,
})
}
}
减速器:
export default function contact(state = initialState, action = {}) {
switch (action.type) {
case CONTACT_POST:
return {
...state,
}
case CONTACT_POST_SUCCESS:
return {
...state,
messages: 'Completed successfully',
error:false,
}
case CONTACT_POST_FAIL:
debugger
return {
...state,
messages: action.error,
error: true,
}
default:
return state
}
}
因为error&消息属性。错误值总是赋值为"0";真";。试着倾听整个状态本身。
const contactState = useSelector((state) => state.contact)
useEffect(() => {
debugger
if (error) {
alert(messages)
}
}, [contactState ])
或者您需要重置错误值&邮件请求上的消息
case CONTACT_POST:
return {
...state, error:false, messages:""
}