我正在用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);
};
};
}
Reducer:
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
Modal.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);