[英]React-native Redux Component not re-rendering on state change with boolean value
调用动作并使用化简版更新商店后,我无法重新渲染组件。 实际的问题是,单击按钮后,我无法显示模态组件。
状态正确更新。 我可以看到我在商店中拥有的布尔值从false
变为true
,但是并没有使用新信息来更新组件。 下面是一些代码:
// Home Page
import React, { Component } from 'react';
import ModalComponent from '../components/modal.component';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { toggleShowModal } from '../actions/modal-actions';
class HomePage extends Component {
state = {
// some values
showModal: false,
};
// added on edit
componentWillReceiveProps(nextProps) {
if (nextProps !== this.props) {
this.setState({
showModal: nextProps.showModal,
})
}
}
_toggleModalVisibility = () => {
// redux action
this.props.toggleShowModal();
}
render() {
<ModalComponent isVisible={this.state.showModal} />
}
}
const mapStateToProps = (state) => {
return {
showModal: state.showModal,
};
};
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ toggleShowModal }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
// Actions
import { SHOW_MODAL } from './types';
export const toggleShowModal = () => dispatch => {
dispatch({
type: SHOW_MODAL,
showModal: true,
});
};
// Reducers (reducers are combined in another file and work fine)
import { SHOW_MODAL } from '../actions/types';
const initialState = {
showModal: false,
};
export const modalReducer = (state = initialState, action) => {
switch (action.type) {
case SHOW_MODAL:
return {
...state,
showModal: action.showModal,
};
default:
return state;
}
};
似乎发生的事情是使用showModal: true
更新了商店,但它没有转换为视图。 上面的代码仅是一个示例,因为该项目非常庞大且不堪重负。 我在Redux中的其他部分工作正常,由于某种原因,这对我不起作用。
这是一个有关我的实时应用程序中发生的事情的简短视频。状态似乎发生了变化,但是直到我执行类似尝试在FlatList
面上的FlatList
上滚动时,才更新视图。
const mapStateToProps = (state) => {
return {
showModal: state.showModal,
};
};
正如我在上面的代码中看到的那样,您正在使用state.showModal
来获取showModal变量,那么您将无法使用,因为您已经在化state.showModal
中使用了一个对象,因此它应该类似于
return {
showModal: state.reducerName.showModal,
};
其中reducerName是您在CombineReducers内部使用的reducer键
还有一件事,当您比较两个对象时,您的componentWillReceiveProps逻辑也不起作用。
我建议您使用componentDidUpdate()
因为不建议使用cWRP。 并检查比较this.props.showModel而不是this.props。 例如
this.props.showModal !== nextProps.showModal
您可以在此处了解有关对象相等性的更多信息
http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html
感谢您的所有帮助。 我发现我没有正确导出减速器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.