You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MapStateToProps未触发问题排查求助

问题:Redux Logout Action触发后组件未捕获状态变化

我知道类似的问题已经被问过好多次了,但我翻遍了各种资料还是没解决。情况是这样的:当触发AUTHENTICATION_LOGOUT这个action时,我能追踪到reducer确实返回了新的状态对象,但组件里的connect就是没捕获到状态变化,导致mapStateToProps根本不执行。我明明返回了新的状态对象,按道理Redux应该能识别出这是状态变更而不是修改原状态,对吧?会不会是Redux或者相关依赖的bug,或者版本不兼容的问题?麻烦大家帮忙看看,谢谢了!

相关代码片段

auth_actions.js

export const appLogout = () => async dispatch => { 
  await AsyncStorage.removeItem(USER); 
  dispatch({ type: "AUTHENTICATION_LOGOUT" }); 
};

auth_reducer.js

export default function (state = {}, action) { 
  switch (action.type) { 
    case "AUTHENTICATION_SUCCESS": 
      return { user: action.payload }; 
    case "AUTHENTICATION_LOGOUT": 
      return {user: null }; 
    default: 
      return state; 
  } 
}

reducers/index.js

export default combineReducers({ search, auth });

AuthComponent.js

import React, { Component } from 'react'; 
import { Text, TouchableOpacity, View } from 'react-native'; 
import { connect } from 'react-redux'; 

class AuthScreen extends Component { 
  ... 
} 

function mapStateToProps(state) { 
  let { auth } = state; 
  return { user: auth.user }; 
} 

export default connect(mapStateToProps, actions)(AuthScreen);

Store配置代码

const store = createStore( 
  reducers, 
  {}, 
  compose( 
    applyMiddleware(thunk) 
  ) 
); 

export default store;

App.js

import store from './store'; 
import { Provider } from 'react-redux'; 

export default class App extends React.Component { 
  render() { 
    return ( 
      <Provider store={store}> 
        <MainNavigation /> 
      </Provider> 
    ); 
  } 
}

package.json依赖

"dependencies": { 
  "axios": "^0.18.0", 
  "expo": "^27.0.0", 
  "react": "16.3.1", 
  "react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz", 
  "react-redux": "^5.0.7", 
  "redux": "^3.7.2", 
  "redux-thunk": "^2.2.0" 
}

问题解决更新

经过一番死磕排查,我终于找到问题根源了:这个AuthScreen组件在触发logout的时候已经被卸载了,所以它自然接收不到任何状态更新。我通过在组件里加componentWillUnmount钩子验证了这一点——触发logout时这个钩子确实执行了。之前一直纠结状态修改的方式,完全是被相关讨论带偏了。感谢所有给我提供思路的朋友!

内容的提问来源于stack exchange,提问作者BlackLog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:51:25