尝试访问this.props.state值时未定义
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完成动作后,我在组件道具中获得了状态对象
我可以从Chrome DevTools $r.props.state.test.title
访问它,但无法从渲染功能访问它
例如,我可以从this.props.params.movieID
获取价值,但无法通过mapStateToProps
修改任何参数
如何在我的div中添加this.props.state.test.title
值?
答案 0 :(得分: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>
);
}
}