[英]Why Redux doesn't re-render component?
我有一個componentDidMount componentDidMount()
方法的組件,它從服務器獲取信息,如下所示:
componentDidMount() {
this.getAccount();
}
getAccount = async () => {
try {
this.res = await API.get(`account`, {});
this.props.setData(this.res.data);
} catch (err) {
this.props.history.push(`/add`);
}
}
我有一個存儲信息的reducer:
const initialState = {}
const accountReducer = (state = initialState, action) => {
if (action.type === 'SET_ACCOUNT_DATA') {
return action.data;
} else {
return state;
}
}
export default accountReducer;
但是我的組件在執行操作后不會重新渲染。 為什么? 我的行動代碼是:
export const setData = (data) => {
return {
type: 'SET_ACCOUNT_DATA',
data
}
}
請幫忙,我做錯了什么?
更新:我的地圖方法是:
const mapStateToProps = (state) => ({
})
const mapDispatchToProps = (dispatch) => {
return {
setData: (data) => {
return dispatch(setData(data));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Account);
Mu動作import
是正確的。 經過。
在你的reducer中你可能想要復制原始狀態並添加你的更改,所以我認為你的reducer應該看起來像:
const accountReducer = (state = initialState, action) => { if (action.type === 'SET_ACCOUNT_DATA') { return {...state, data: action.data}; } else { return state; } }
如果您的組件有mapStateToProps()
,它返回空對象,那么如果沒有props / state更改,組件將不會重新渲染...您的mapStateToProps()
方法應該如下所示:
const mapStateToProps = state => ({ data: state.yourReducer.yourDataFromStore })
你通過把console.log('state :::',state)檢查了嗎? 在mapStateToProps()里面? 它又被召喚了嗎? 你也試試這個嗎?
const accountReducer = (state = initialState, action) => {
if (action.type === 'SET_ACCOUNT_DATA') {
return Object.assign({}, state, {...state, data:action.data });
} else {
return state;
}
}
並在mapStateToProps中
const mapStateToProps = (state)=>({
data: state.reducername.data
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.