[英]react useEffect hook triggers only once although update redux store
SImple hook component below, when submitting form it throws exception and useEffect hook triggers and prompts error message fine,下面简单的钩子组件,提交表单时抛出异常,useEffect钩子触发并提示错误信息很好,
if submit again for some reason useEffect not triggers..如果由于某种原因再次提交 useEffect 不会触发..
I can assure you submit, action works as expected since I follow up steps with debuggers.. it doesn't step into useEffect after first submit..我可以向您保证提交,操作按预期工作,因为我使用调试器跟进步骤..第一次提交后它不会进入 useEffect ..
component:零件:
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))
}
action:行动:
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,
})
}
}
reducer:减速器:
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
}
}
Because there is no value change for error & message property.因为错误和消息属性没有值变化。 Error value is always assigning as "true".错误值始终指定为“真”。 Try listening the entire state itself.尝试聆听整个 state 本身。
const contactState = useSelector((state) => state.contact)
useEffect(() => {
debugger
if (error) {
alert(messages)
}
}, [contactState ])
Or you need to reset the error value & message on post request或者您需要在发布请求时重置错误值和消息
case CONTACT_POST:
return {
...state, error:false, messages:""
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.