我正在构建一个react本机应用程序但是我注意到,只要我将一些操作发送到redux存储,就不会调用componentWillReceiveProps
,只有在我刷新屏幕时才会调用它。
组件
import React from 'react';
import { connect } from 'react-redux';
import { renderLogin } from '../../components/Auth/Login';
class HomeScreen extends React.Component {
componentWillReceiveProps(props) {
const { navigate } = props.navigation;
if (props.userData.authenticated) {
navigate('dashboard')
}
}
login = () => {
renderLogin()
}
render() {
const { navigate } = this.props.navigation;
return (
<Container style={styles.home}>
// Some data
</container>
)
}
}
function mapStateToProps(state) {
return {
userData: state.auth
}
}
export default connect(mapStateToProps)(HomeScreen)
RenderLogin
export function renderLogin() {
auth0
.webAuth
.authorize({
scope: 'openid email profile',
audience: 'https://siteurl.auth0.com/userinfo'
})
.then(function (credentials) {
loginAction(credentials)
}
)
.catch(error => console.log(error))
}
则loginAction
const store = configureStore();
export function loginAction(credentials) {
const decoded = decode(credentials.idToken);
saveItem('token', credentials.idToken)
store.dispatch(setCurrentUser(decoded));
}
export async function saveItem(item, selectedValue) {
try {
await AsyncStorage.setItem(item, JSON.stringify(selectedValue));
const decoded = decode(selectedValue);
} catch (error) {
console.error('AsyncStorage error: ' + error.message);
}
}
答案 0 :(得分:0)
我相信您的问题与mapStateToProps
有关,即当您在redux中更新状态但尚未将新状态映射到道具时,HomeScreen
中的道具将保持不变, componentWillReceiveProps
只会被触发一次。
阅读Proper use of react-redux connect和Understanding React-Redux and mapStateToProps。