jkurs jkurs - 29 days ago 10
React JSX Question

React native connect function not passing action to child component through props

I am just getting familiarized with redux and have been reading that I am supposed to pass in action creators through the parent of the app, and through mapStateToProps, mapDispatchToProps, and the connect function I should be able to pass actions. However, when I call in the child component this.props. the function is nonexistent, so it seems that it is not being passed properly.

I would greatly appreciate assistance.

Note: I left out some things like imports and the reducer to be more concise.

login.js:

export function login(token, id) {
console.log('login action');
return {
type: 'LOG_IN',
token,
id,
};
}


index.ios.js:

import * as actionCreators from './actions/login'

const store = createStore(RootReducer, undefined, autoRehydrate());
persistStore(store);

class App extends Component {
constructor(props) {
super(props);
state = {
token: '',
id: '',
store: store,
};
}

render() {
return (

<Provider store={ state.store }>
<View style = {styles.container}>
<LoginView/>
</View>
</Provider>
);
}
}

AppRegistry.registerComponent('App', () => App);

function mapStateToProps(state) {
return {
token: state.token,
id: state.id
}
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({actionCreators}, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(App);


loginView.js:

export class LoginView extends View {

static propTypes = {}

static defaultProps = {}

constructor(props) {
console.log(props);
super(props)
this.state = {
user: '',
token: '',
id: '',
}
this.onLogin = this.onLogin.bind(this);
}

onLogin() {
console.log("on login1");
this.props.login({token: this.state.token, id: this.state.id});
console.log("on login");
}


And basically what happens is that when the onLogin() function is evoked directly above, it states that this.props.login is not a function. What is the reasoning for this and how can I fix it?

Answer

You're connecting the App component, so that will have this.props.onLogin(). However, you're not passing onLogin as a prop to <LoginView />. You need to either render <LoginView onLogin={this.props.onLogin} />, or connect LoginView also and include onLogin as part of that component's connection.