[英]React Native - Redux ~ Props updating when not getting called
I am experiencing an issue with React Native whilst using Redux. 我在使用Redux时遇到React Native问题。
I am using a Redux state to show/hide a modal from one component to the other. 我正在使用Redux状态来显示/隐藏从一个组件到另一个组件的模式。 As this seems to be the best solution considering that it is cross component.
考虑到它是跨组件的,因此这似乎是最好的解决方案。
I have the modal opening and closing perfectly fine, and that works exactly how it show. 我的模式打开和关闭非常完美,并且显示效果完全一样。 However, when I click on this, it seems as though the props for the parent component are getting updated to the initial state again and I'm unsure as to why.
但是,当我单击此按钮时,似乎父组件的道具再次被更新为初始状态,我不确定原因。
Parent Component: 父组件:
const mapStateToProps = state => {
return {
modalVisible: state.modals.addRoomModalVisible
}
};
const mapDispatchToProps = dispatch => {
return {
onMakeAddRoomModalActive: () => dispatch(makeAddRoomModalVisible())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(RoomsScreen);
Child Component 子组件
const mapStateToProps = state => {
return {
rooms: state.rooms.rooms
}
};
const mapDispatchToProps = dispatch => {
return {
onGetRooms: () => dispatch(getRooms())
}
};
export default connect(mapStateToProps, mapDispatchToProps)(RoomList);
Modals Reducer 模态减速机
import { HIDE_ADD_ROOM_MODAL, SHOW_ADD_ROOM_MODAL } from "../actions/actionTypes";
const initialState = {
addRoomModalVisible: false
};
const modalsReducer = (state = initialState, action) => {
switch (action.type) {
case SHOW_ADD_ROOM_MODAL:
return {
...state,
addRoomModalVisible: true
};
case HIDE_ADD_ROOM_MODAL:
return {
...state,
addRoomModalVisible: false
};
default:
return initialState;
}
};
export default modalsReducer;
It seems the issue lies when I call the onMakeAddRoomModalActive
prop. 似乎问题出在我调用
onMakeAddRoomModalActive
道具时。 I have console logged out and the state is getting reset and the this.props.rooms
is getting set to and empty array which is the initialState
object which I have defined. 我退出了控制台,状态正在重置,
this.props.rooms
设置为空数组,这是我定义的initialState
对象。
The issue lay within all of my reducers. 问题出在我所有的减速器中。
At the end of each reducer case statement I did a default which set the state to be the initialState
which was defined at the top of the reducer. 在每个reducer case语句的末尾,我做了一个默认操作,将状态设置为在reducer顶部定义的
initialState
。
I needed to change this to return state
instead. 我需要将其更改为返回
state
。
const modalsReducer = (state = initialState, action) => {
switch (action.type) {
case SHOW_ADD_ROOM_MODAL:
return {
...state,
addRoomModalVisible: true
};
case HIDE_ADD_ROOM_MODAL:
return {
...state,
addRoomModalVisible: false
};
default:
return state;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.