![](/img/trans.png)
[英]React/Redux - Can't send a store value into props of a component (mapStateToProps)
[英]Can't access React props modified by Redux MapStateToProps
嘗試訪問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
修改的任何參數
如何將this.props.state.test.title
值放入div?
在渲染函數內部,檢查標題是否未定義,因為在解析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>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.