我正在将应用程序从React迁移到React Native,并且遇到Redux的问题而没有将操作分派给Reducer。
我的根组件如下所示:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux';
import Main from '../main/main';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class App extends Component {
render() {
console.log('Rendering root.js component');
console.log(this.props);
const { dispatch, isAuthenticated, errorMessage, game, communication } = this.props
return (
<View style={styles.appBody}>
<Main
dispatch={dispatch}
game={game}
communication={communication}
/>
</View>
)
}
}
App.propTypes = {
dispatch: PropTypes.func.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
errorMessage: PropTypes.string,
}
function mapStateToProps(state) {
const { auth } = state
const { game } = state
const { communication } = state
const { isAuthenticated, errorMessage } = auth
return {
isAuthenticated,
errorMessage,
game,
communication
}
}
const styles = StyleSheet.create({
appBody: {
}
});
export default connect(mapStateToProps)(App)
然后,'lobby'子组件具有Redux的调度功能,作为传递给它的道具。此组件连接到单独的javascript文件,并将props传递给它,以便该单独的文件可以访问调度函数:
componentWillMount() {
coreClient.init(this);
}
在该文件中,我这样做:
const init = function(view) {
socket.on('connectToLobby', (data) => {
console.log('Lobby connected!');
console.log(data);
console.log(view.props) // shows the dispatch function just fine.
view.props.dispatch(connectLobbyAction(data));
});
}
动作本身也会显示我放在那里的控制台日志,只是它从不发送。
export const LOBBY_CONNECT_SUCCESS = 'LOBBY_CONNECT_SUCCESS';
export function connectLobbyAction(data) {
console.log('Action on connected to lobby!')
return {
type: LOBBY_CONNECT_SUCCESS,
payload: data
}
}
我觉得有点失落,会很感激一些反馈:)
编辑:Reducer片段:
var Symbol = require('es6-symbol');
import {
LOBBY_CONNECT_SUCCESS
} from './../actions/actions'
function game(state = {
//the state, cut to keep things clear.
}, action) {
switch (action.type) {
case LOBBY_CONNECT_SUCCESS:
console.log('reducer connect lobby')
return Object.assign({}, state, {
...state,
user : {
...state.user,
id : action.payload.id,
connected : action.payload.connected
},
match : {
...state.match,
queuePosition : action.payload.position,
players : action.payload.playerList,
room : 'lobby'
},
isFetching: false,
})
default:
return state
}
}
const app = combineReducers({
game,
//etc.
})