我遇到以下问题,我在React中创建了一个组件,我主要尝试使用this.props.dispatch()
方法。但是,当我尝试在我创建的函数中引用this.props时,我在控制台中收到错误,说明以下内容。
未捕获的TypeError:无法读取属性' dispatch'未定义的
问题:为什么不能在我自己添加的功能中使用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;
答案 0 :(得分:4)
您正在使用错误的上下文调用this.handleResize
<强>替换强>
window.addEventListener('resize', this.handleResize );
要强>
window.addEventListener('resize', this.handleResize.bind(this) );
或者在constructor
this.handleResize = this.handleResize.bind(this)
答案 1 :(得分:1)
只需修改你的构造函数 -
constructor(props) {
super(props);
this.handleResize = this.handleResize.bind(this);
}