Reactjs Redux reducer状态更改不';t触发器生命周期方法
我试图在reducer在React生命周期方法(如componentdiddupdate或componentWillUpdate)中更新后获得新状态,并需要相应地重新渲染组件。但我在控制台中看到了更改的日志,但它既不会触发lifeCycleMethods,也不会触发组件重新加载 最初,我在reducer中使用Object.assign,如下所示:Reactjs Redux reducer状态更改不';t触发器生命周期方法,reactjs,redux,Reactjs,Redux,我试图在reducer在React生命周期方法(如componentdiddupdate或componentWillUpdate)中更新后获得新状态,并需要相应地重新渲染组件。但我在控制台中看到了更改的日志,但它既不会触发lifeCycleMethods,也不会触发组件重新加载 最初,我在reducer中使用Object.assign,如下所示: return Object.assign({}, state, { emailAddr: action.data
return Object.assign({}, state, {
emailAddr: action.data
});
但在阅读了一些StackOverflow的答案后意识到这是行不通的。所以,我也尝试了下面的一些答案
state = {
...state,
emailAddr: action.data,
};
console.log("newState: ", state);
return state;
及
所有这些都不会触发任何生命周期方法
emailReducer.js
export default function emailInfo(state = {
emailAddr: '',
}, action){
switch(action.type){
case 'SENT_EMAIL_DATA':
debugger;
console.log("state when email address sent: ", state);
console.log("action.data when email address sent: ", action.data);
// return Object.assign({}, state, {
// emailAddr: action.data
// });
state = {
...state,
emailAddr: action.data,
};
console.log("newState: ", state);
return state;
// return {
// ...state,
// emailAddr: action.data,
// };
default: {
return {
...state
}
}
}
}
action.js
import { API_URL } from '../global';
import axios from 'axios';
export const sentEmailData = data => {
return {
type: 'SENT_EMAIL_DATA',
data
};
};
export function submitEmail( data) {
return dispatch => {
return axios.post(API_URL, {
emailAddr: data
})
.then(response => {
if (response.data.errors === null ) {
console.log("response 2222: ", response);
dispatch(sentEmailData(response));
} else {
throw new Error(response.data.errors[0].statusMessage);
}
})
.catch(err =>{
console.log("err 2222: ", err);
});
}
}
我知道还原器必须返回新对象。如果我们改变对象,组件就不会得到重新渲染。但是不确定我还缺少什么好的,所以任何其他用户都有相同的问题,除了在我的组件中我没有使用MapStateTops之外,我的一切都是正确的。因此,我的组件无法侦听存储区中的更改 我读了这篇文章后意识到了这一点。在阅读了@andrewchumich的评论后,我改变了组件,一切都开始工作了
您能否共享您希望重新渲染的组件,以及如何使用
connect
将其连接到商店?非常感谢您的快速响应。在阅读了上面的文章之后,我找到了一个解决方案。但是,你的猜测是对的,问题出在我的连接上
import { API_URL } from '../global';
import axios from 'axios';
export const sentEmailData = data => {
return {
type: 'SENT_EMAIL_DATA',
data
};
};
export function submitEmail( data) {
return dispatch => {
return axios.post(API_URL, {
emailAddr: data
})
.then(response => {
if (response.data.errors === null ) {
console.log("response 2222: ", response);
dispatch(sentEmailData(response));
} else {
throw new Error(response.data.errors[0].statusMessage);
}
})
.catch(err =>{
console.log("err 2222: ", err);
});
}
}