![](/img/trans.png)
[英]Stateful react-native functional component don't re-render when redux connected state change
[英]React native with connect helper from redux doesn't re-render when state change?
我使用reactJS
並且我知道一個由connect
助手包裝的組件,當其reducer's state
更改時,它會偵聽特定的reducer
,從而導致該組件re-render
。
我不知道為什么相同的程序不能對react-native
起作用,我測試了action creators
和化reducers
並檢查了它們返回新state
,並且當我檢查componentWillRecieveProps
我發現正確返回了新狀態並且該組件不會重新渲染。
減速器
const INITIAL = {
isSigned: null
}
export default (state = INITIAL, action) => {
switch(action.type){
case SIGNED_IN : return {...state, isSigned: true};
case LOGGED_OUT: return {...state, isSigned: false};
default: return state;
}
}
零件
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import * as actions from '../../actions';
class Loading extends Component {
constructor(props){
super(props);
}
componentDidMount(){
this.props.checkSigned();
switch(this.props.isSigned){
case null : return;
case false : this.props.navigation.navigate('Auth');
case true : this.props.navigation.navigate('App')
}
}
render(){
return (
<ActivityIndicator size="large" color="black" />
)
}
}
const mapStateToProps = ({signed}) => {
const {isSigned} = signed;
return {
isSigned
}
}
export default connect(mapStateToProps, actions)(Loading);
操作
export const SIGNED_IN = 'SIGNED_IN';
export const LOGGED_OUT = 'LOGGED_OUT';
//Action Creators
export const checkSigned = () => async dispatch => {
let token = await AsyncStorage.getItem('fb_token');
if(token){
dispatch({type: SIGNED_IN})
}
dispatch({type: LOGGED_OUT})
}
您需要使用bindActionCreators
將您的操作作為道具進行分派
import { bindActionCreators } from 'redux';
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
const mapStateToProps = state => {
return {
isSigned: state.isSigned
}
}
export default connect(mapStateToProps, actions)(Loading);
//在操作中,您需要修復操作代碼
export const checkSigned = () => async dispatch => {
let token = await AsyncStorage.getItem('fb_token');
if(token){
dispatch({type: SIGNED_IN});
} else {
dispatch({type: LOGGED_OUT});
}
}
我認為問題在於您正在componentDidMount
運行狀態更改邏輯。 重新渲染組件時, componentDidMount
不會運行,但是componentDidUpdate
會運行。 把你的邏輯放在那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.