我遇到以下問題,我在React中創建了一個組件,主要嘗試使用this.props.dispatch()
方法。然而,當我嘗試在我創建的函數中引用this.props時,在控制檯中出現以下錯誤。訪問this.props時與redux反應組件未定義
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;
你可以閱讀更多[文件](HTTPS://facebook.github。 IO /反應/文檔/可重複使用-components.html#ES6類) –