[英]Stateful react-native functional component don't re-render when redux connected state change
I've started using hooks recently with react-native, so i have this connected component with a button that changes depending on a redux state.我最近开始在 react-native 中使用钩子,所以我让这个连接的组件带有一个根据 redux 状态而改变的按钮。 The button changes when redux state is updated inside the component, but not if it is from outside.
当 redux 状态在组件内部更新时,按钮会发生变化,但如果是从外部更新则不会。
here is my button:这是我的按钮:
<TouchableOpacity
style={styles.goPremiumContainer}
onPress={() => pay()}>
{props.premiumLoading ? (
<ActivityIndicator size="small" color="#fff" />)
:
(<Text style={styles.goPremium}>
{i18n.t('premium:go_premium')}
</Text>)}
</TouchableOpacity>
//
//
//
const mapStateToProps = state => {
return {
premiumLoading: state.premiumLoading,
};
};
export default withNamespaces([], {wait: true})(
connect(mapStateToProps)(Premium),
);
also the reducer:还有减速器:
const initialState = false;
function updateButtonLoading(state = initialState, action) {
let nextState;
switch (action.type) {
case 'LOADING':
nextState = true;
return nextState || state;
case 'NOT_LOADING':
nextState = false;
return nextState || state;
default:
return state;
}
}
export default updateButtonLoading;
To update the button i call this action function:要更新按钮,我调用此操作函数:
async updatePremiumButton(actionType) {
console.log('actionType',actionType)
const action = {type: actionType};
const unsubscribe = store.subscribe(() => true);
await store.dispatch(action);
await unsubscribe();
},
THANKS!谢谢!
The issue is the logic inside your reducer.问题是减速器内部的逻辑。
switch (action.type) {
case 'LOADING':
nextState = true;
return nextState || state;
case 'NOT_LOADING':
nextState = false;
return nextState || state;
default:
return state;
}
It appears that what you really want to do is return the value you assign nextState
, but the logic reads differently.看起来您真正想要做的是返回您分配给
nextState
的值,但逻辑读取不同。
Currently the logic reads: If nextState
is truthy use it, else return previous state.目前的逻辑是:如果
nextState
为真,则使用它,否则返回先前的状态。
In the NOT_LOADING
case, you are intending to return the value false
, but the logic reads: If false
is true, return false
, else return true
.在
NOT_LOADING
情况下,您打算返回值false
,但逻辑如下:如果false
为 true,则返回false
,否则返回true
。 So you can see why this would never work.所以你可以明白为什么这永远不会奏效。
Instead, simplify the cases and just return what you want the state to be.相反,简化案例并返回您想要的状态。 The
||
||
conditions don't seem to be necessary.条件似乎不是必需的。
function updateButtonLoading(state = initialState, action) {
switch (action.type) {
case 'LOADING':
return true;
case 'NOT_LOADING':
return false;
default:
return state;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.