【发布时间】:2019-05-07 16:37:40
【问题描述】:
我最近注意到我的应用程序中 Redux 的一个非常奇怪的行为,我想与你分享。当我在设置中单击此 TouchableOpacity 以断开连接时,出现以下错误:
TypeError: 无法读取属性 first_name of null
来自 Homepage.js
所以我的代码正在为我不应该去的页面中的那个组件触发一个错误。
Homepage.js
<AppText textStyle={styles.title}>
Welcome {userReducer.infos.first_name}
</AppText>
应该发生的工作流程是用户单击断开连接按钮,然后调用 tryLogout 函数,该函数触发类型为“LOGOUT”的操作。然后此操作设置为空用户相关数据和信息以及一些额外的布尔值。状态得到更新,然后应该重新渲染 UI 并调用 componentWillUpdate()。在那里,我检查我的状态以将用户重定向到登陆/未连接导航。
我尝试在我的 reducer 和我的代码处理中评论 infos: null 没有错误。
这个变量在我的应用程序中没有要求重定向到任何页面。
调试起来可能看起来很复杂,因为问题肯定比看起来更深。无论如何,也许有人已经遇到过类似的问题,所以我在这里为您提供尝试解决问题的潜在要素。
Settings.js
import { tryLogout } from '@actions/user'
const mapDispatchToProps = dispatch => ({
tryLogout: () => dispatch(tryLogout()),
})
class Settings extends React.Component<Props, State> {
// What should normally happen
componentDidUpdate(prevProps: Props) {
const { userReducer, navigation } = this.props
if (
prevProps.userReducer.isSignedUp !== userReducer.isSignedUp ||
prevProps.userReducer.isLoggedIn !== userReducer.isLoggedIn
) {
if (!userReducer.isSignedUp && !userReducer.isLoggedIn) {
navigation.navigate('Landing')
}
}
}
// Inside my render() method
<AppTouchableOpacity
onPress={() => tryLogout()}
style={styles.touchableOpacity}
>
Disconnect
</AppTouchableOpacity>
}
actions/user.js
export const tryLogout = (): Function => (dispatch: Function) => {
const logout = () => ({
type: LOGOUT,
})
dispatch(logout())
}
reducers/user.js
case LOGOUT:
return {
...state,
data: null,
infos: null,
isLoggedIn: false,
isSignedUp: false,
}
App.js(我正在使用 React Navigation)
const LandingScenes = {
Welcome: { screen: WelcomeScreen },
{ /* Some other screens */ }
}
const LandingNavigator = createStackNavigator(LandingScenes, {
initialRouteName: 'Welcome',
defaultNavigationOptions: {
header: null,
},
})
const SecuredScenes = {
Homepage: { screen: HomepageScreen },
Settings: { screen: SettingsScreen },
{ /* Some other screens */ }
}
const SecuredNavigator = createStackNavigator(SecuredScenes, {
initialRouteName: 'Homepage',
defaultNavigationOptions: {
header: null,
},
})
export default createAppContainer(
createSwitchNavigator(
{
Landing: LandingNavigator,
Secured: SecuredNavigator,
},
{
initialRouteName: 'Landing',
}
)
)
【问题讨论】:
标签: javascript reactjs react-native redux react-navigation