我刚开始学习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)时被中断呈现,因为每个调度都会触发重新呈现。
如何在调度操作后导航到其他屏幕?我可以以某种方式发送一个动作而不会触发重新渲染吗?
答案 0 :(得分:1)
尝试将所有这些移至
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));
}
你可能需要调整你在render方法中使用的一些const