【发布时间】:2016-07-28 07:06:43
【问题描述】:
我在 React 中创建了一个组件时遇到以下问题,我主要尝试使用 this.props.dispatch() 方法。但是,当我尝试在我创建的函数中引用 this.props 时,控制台中出现错误,提示如下。
Uncaught TypeError: Cannot read property 'dispatch' of undefined
问题:为什么不能在我自己添加的函数中使用this.props,例如handleResize() 当this.props 可用于componentWillMount(), componentDidMount(), 等默认反应函数时
这是导致上述错误的函数。
handleResize() {
console.log( "handle function getting called" );
this.props.dispatch( changeListHeight( window.innerHeight ) );
}
这是我的完整反应组件
import React, {Component} from 'react';
import Avatar from 'material-ui/Avatar';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { connect } from "react-redux";
import { fetchMessages } from '../actions/messageActions';
import { changeListHeight } from '../actions/appActions';
import {
blue300,
indigo900,
orange200,
deepOrange300,
pink400,
purple500,
} from 'material-ui/styles/colors';
@connect((store) => {
return {
messages: store.messages.messages,
app: store.app
};
})
class Items extends Component {
constructor(props) {
super(props);
this.props.dispatch( changeListHeight( window.innerHeight ) );
}
componentWillMount() {
this.props.dispatch( fetchMessages() );
}
componentDidMount() {
console.log( this.props );
window.addEventListener('resize', this.handleResize ); //event to handle resizing the message list
this.refs.chatList.onscroll = function() { this.handleScroll }; //event to keep the freshest messages in view
}
handleResize() {
console.log( "handle function getting called" );
this.props.dispatch( changeListHeight( window.innerHeight ) );
}
handleScroll() {
console.log( "handle function getting called" );
//console.log(this.refs.chatList);
//let isScrolledToBottom = this.chatList.scrollHeight - this.chatList.clientHeight <= this.chatList.scrollTop + 1;
}
render() {
let listStyle = {
height: (this.props.app.chatListHeight - (35 + 64 + 8 + 135)),
overflowY: "auto"
}
let listItemStyle = {
margin: 5,
};
return (
<MuiThemeProvider>
<List className="chat-list" style={listStyle} ref="chatList">
{this.props.messages.map(function(message){
return <ListItem
key={message.id}
disabled={true}
leftAvatar={
<Avatar
color={deepOrange300}
backgroundColor={purple500}
size={30}
style={listItemStyle}
>
{message.name.charAt(0)}
</Avatar>
}>
{message.msg}
</ListItem>;
})}
</List>
</MuiThemeProvider>
);
}
}
export default Items;
【问题讨论】:
标签: javascript reactjs redux react-redux