[英]Can't access React props modified by Redux MapStateToProps
Got undefined when trying to access this.props.state value 尝试访问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);
After redux complete the action i've got state object in component props 在redux完成动作之后,我在组件道具中有了状态对象
I can access it from Chrome DevTools $r.props.state.test.title
but can't access it from render function 我可以从Chrome DevTools
$r.props.state.test.title
访问它,但不能从渲染功能访问它
For example I can get value from this.props.params.movieID
but can't get any params modified by mapStateToProps
例如,我可以从
this.props.params.movieID
获取值,但无法获取由mapStateToProps
修改的任何参数
How can I put this.props.state.test.title
value in my div? 如何将
this.props.state.test.title
值放入div?
Inside your render function check if the title is undefined because the render function is being called before your redux action is resolving. 在渲染函数内部,检查标题是否未定义,因为在解析redux操作之前已调用了渲染函数。 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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.