2016-07-17 81 views
0

了未定義試圖訪問this.props.state值無法訪問陣營的終極版MapStateToProps修改道具

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); 

後Redux的完成組件的道具

動作我有狀態對象時Redux DevTools

我可以從Chrome的DevTools $r.props.state.test.title訪問它,但不能從渲染功能

訪問它爲電子商務xample我可以從this.props.params.movieID得到值,但不能得到任何修改的參數mapStateToProps

如何將this.props.state.test.title值放入我的div中?

+0

你可以粘貼實際的錯誤,你究竟得到了什麼樣的未定義? – Daniel

回答

2

在渲染函數中檢查標題是否未定義,因爲渲染函數在您的redux動作解析之前被調用。一旦你的狀態被更新並且你的組件呈現它應該顯示第二次。

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> 
); 
} 
}