首页 > 解决方案 > react-native 组件在更新 redux 状态后不会重新渲染

问题描述

我正在用 react-native 构建一个应用程序,我正在使用 redux。我正在使用 websocket 来更新我的 redux 状态。在 Web 界面中,我单击一个按钮,它会增加我的应用程序的分数。我想要做的是在每次 redux 状态更新时显示一个模式,这是我的代码:

Websocket.js:


import RoutesApp from './constantApi'
import { store } from '../store/configStore'

export function initWebSocketConnection(teamName) {
    var ws = new WebSocket('ws://' + RoutesApp.HostName + '/ws?teamId=' + teamName);

    ws.onopen = () => {
        // connection opened
        // nothing special to do
    };

    ws.onmessage = (e) => {
        // a message was received
        const message = JSON.parse(e.data);
        switch (message.messageType) {
            case 'giveaway/message':
                store.dispatch({type: 'GIVEAWAY', value: message});
                break
        };

        ws.onerror = (e) => {
            // an error occurred
            console.log(e.message);
        };

        ws.onclose = (e) => {
            // connection closed
            console.log(e.code, e.reason);
        };
    };
  }

减速机:


const initialState = {
  notification: []
}

const teamPaths = (state = initialState, action) => {
  let nextState
  switch (action.type) {
    case 'GIVEAWAY':
      nextState = {
        ...state,
      }
      nextState.notification.push('Vous avez gagné une charge de pouvoir')
      break
    default:
  }
  return nextState || state
}

export default teamPaths

模态.js

lass ModalGeneral extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      modalVisible: false,
    }
  }

  visibleYe(){
    if(this.props.notification.length > 0){
      return !this.state.modalVisible
    }else if(this.props.notification.length === 0){
      return this.state.modalVisible
    }
  }

  render() {
    return (
      <Modal
        style={{ justifyContent: 'center' }}
        animationIn="slideInUp"
        animationInTiming={1000}
        animationOutTiming={1000}
        isVisible={this.visibleYe()}
      >
        <View style={styles.container}>
          <View style={styles.titleModal}>
            <Text style={styles.title}>{this.props.notification}</Text>
          </View>
      </Modal>
    )
  }
}

const mapStateToProps = state => {
  return {
    notification: state.notification
  }
}

export default connect(mapStateToProps)(ModalGeneral)

但是当我在另一个组件中调用我的模态组件时,模态仅在组件呈现时打开,然后一切都像我想要的那样,消息推送显示但是为什么 redux 状态更新不会使组件重新呈现?我看到了很多这样的解决方案:

const mapStateToProps = state => ({
  notification: state.myReducer.notificaion
})

当然替换为我的减速器的名称:teamData,但它不起作用并抛出错误:

cannot read property notification of undefined

我真的很需要这个,我不明白这个问题,我错过了什么?

[编辑]

configStore.js

import { createStore } from 'redux'
import teamData from './reducers/teamData'


export const store = createStore(teamData);

标签: react-nativereact-redux

解决方案


推荐阅读