Natio Li
Natio Li

Reputation: 41

Can't access React props modified by Redux MapStateToProps

Got undefined when trying to access this.props.state value

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';

const mapStateToProps = ({ movies }) => ({
  state: movies,
});

class App extends Component {

  componentDidMount() {
    this.props.addMovie({ title: 'Movie' }); //redux action
  }

  render() {
    const { state } = this.props;
    console.log(state.test);       //Object {title: "Movie"}
    console.log(state.test.title); //Uncaught TypeError: Cannot read property 'title' of undefined
    return (
      <div>Hello {state.test.title}!</div> //doesn't work
    );
  }
}

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

After redux complete the action i've got state object in component props

Redux DevTools

I can access it from Chrome DevTools $r.props.state.test.title but can't access it from render function

For example I can get value from this.props.params.movieID but can't get any params modified by mapStateToProps

How can I put this.props.state.test.title value in my div?

Upvotes: 0

Views: 1395

Answers (1)

Joey
Joey

Reputation: 1155

Inside your render function check if the title is undefined because the render function is being called before your redux action is resolving. Once your state is updated and your component renders it should show up the second time.

render() {
  const { state } = this.props;
  console.log(state.test);
 if(state.test && state.test.title){
   console.log(state.test.title); 
    return (
     <div>Hello {state.test.title}!</div>
   )
} else {
   return (
    <div>No movies listed</div>
  );
 }
}

Upvotes: 2

Related Questions