我刚刚开始学习 react-native 和 redux。我正在尝试实现身份验证方案。我正在使用react-navigation
.
import { authenticate } from './../actions';
const Component = (props) => {
const { dispatch, user } = props;
// user comes from state (using mapStateToProps)
let phone = '';
let password = '';
if (user.errors != null) {
alert(user.errors);
}
if (user.authenticated) {
dispatch(NavigationActions.navigate({ routeName: 'LoggedIn' }));
}
async function onLogin() {
dispatch(authenticate(phone, password));
}
return (
<View>
<TextInput
style={{height: 40, width: '100%', borderColor: 'gray', borderWidth: 1, marginTop: 10}}
placeholder="(xxx) xxx-xx-xx"
keyboardType={'phone-pad'}
onChangeText={(value) => phone = value}
value={phone}
/>
<TextInput
style={{height: 40, width: '100%', borderColor: 'gray', borderWidth: 1, marginTop: 10}}
placeholder="Пароль"
onChangeText={(value) => password = value}
value={password}
/>
<Button
onPress={onLogin}
title="Continue"
/>
</View>
);
}
这是身份验证操作
export function authenticate(phone, password) {
return async dispatch => {
dispatch(authenticating());
let response;
try {
response = await Api.authenticate(phone, password);
}
catch (e) {
dispatch(authenticateFailure(e.error));
return;
}
dispatch(authenticateSuccess(response.token, response.payload));
};
};
所以基本上当authenticate
动作被调度并且用户成功通过身份验证时,我想将用户重定向到下一个屏幕(LoggedIn
)。但重定向后我收到此错误:
Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.
我猜问题是前一个组件在重定向到下一个组件(LoggedIn)时被中断渲染,因为每个调度都会触发重新渲染。
分派操作后如何导航到另一个屏幕?我可以以某种方式在不触发重新渲染的情况下分派动作吗?
尝试将所有这些移动到
componentWillReceiveProps(nextProps) {
// check props you want to use as execution trigger
}
#
const { dispatch, user } = props;
// user comes from state (using mapStateToProps)
let phone = '';
let password = '';
if (user.errors != null) {
alert(user.errors);
}
if (user.authenticated) {
dispatch(NavigationActions.navigate({ routeName: 'LoggedIn' }));
}
async function onLogin() {
dispatch(authenticate(phone, password));
}
你可能需要调整一些你在渲染方法中使用的常量
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句