反应道具不与redux商店更新

本杰明·巴金斯(Benjamin Baggins)

我一直使用react-reduxconnect来配置道具,但是我需要使用reactComponent来使用生命周期方法。我注意到从商店中获取的道具似乎是静态的,并且不会随着商店的更新而更新。

码:

class AlertModal extends Component {

  title
  isOpen
  message

  componentDidMount() {
    const { store } = this.context
    const state = store.getState()
    console.log('state', state)
    console.log('store', store)
    this.unsubscribe = store.subscribe(() => this.forceUpdate())
    this.title = state.get('alertModal').get('alertModalTitle')
    this.isOpen = state.get('alertModal').get('isAlertModalOpen')
    this.message = state.get('alertModal').get('alertModalMessage')
    this.forceUpdate()
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  updateAlertModalMessage(message) {
    this.context.store.dispatch(updateAlertModalMessage(message))
  }
  updateAlertModalTitle(title) {
    this.context.store.dispatch(updateAlertModalTitle(title))
  }

  updateAlertModalIsOpen(isOpen) {
    this.context.store.dispatch(updateAlertModalIsOpen(isOpen))
  }

  render() {

    console.log('AlertModal rendered')
    console.log('AlertModal open', this.isOpen) <======= stays true when in store it is false

    return (
      <View

如何设置titleisOpen以及message使它们反映在任何时候都存储值?

拉文德拉·兰瓦拉(Ravindra Ranwala)

应该是这样的。在您的确认组件中:

const mapStateToProps = (state) => {
  return { modalActive: state.confirmation.modalActive };
}

export default connect(mapStateToProps)(Confirmation);

在减速器索引文件中,应该是这样的:

const rootReducer = combineReducers({
  confirmation: ConfirmationReducer
});

我相信您在这里有一个自己的减速器文件,称为ConfirmationReducer。应该是这样的。

import { ON_CONFIRM } from '../actions';

const INITIAL_STATE = {modalActive: true};
export default function(state = INITIAL_STATE, action) {
  console.log(action);
  switch (action.type) {
    case ON_CONFIRM:
      return { ...state, modalActive: action.payload };
  }

  return state;
}

确保编写自己的动作创建者以创建具有上述类型和布尔类型的相关有效负载的动作。

最后,您应该能够从Confirmation组件内部的商店访问属性,如下所示:

{this.props.modalActive}

您尚未发布完整的代码,因此很难为确切的方案提供解决方案。希望这可以帮助。祝您编码愉快!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章