在这里反应新手。我在componentDidMount函数中尝试获取redux状态对象(this.props.message)的键数组时遇到问题。我希望加载这些消息,以便我的组件可以相应地呈现列表中的键。 问题是,在我的componentDidMount中,当我在console.log(this.props.message)时,我得到了正确的对象,但我的Object.keys(this.props.message)返回一个空数组。为了测试,我在我的一个按钮上添加了一个clickHandler,以使用相同的代码片段查看它是否是一个生命周期问题。当我单击按钮并且我的本地状态正确更改为相应的数组时,一切正常。 任何人都可以对我做错了吗?提前谢谢!
import React from 'react';
import { connect } from 'react-redux';
import _ from 'underscore';
import Message from '../components/Message'
class Inbox extends React.Component{
constructor(props){
super(props);
this.state={
inboxNames:false
}
}
componentDidMount(){
console.log('in componentDidMount', this.props.message)
var newArray = Object.keys(this.props.message)
this.setState({inboxNames:newArray})
}
clickHandler(){
var newArray = Object.keys(this.props.message);
this.setState({inboxNames:newArray})
}
render(){
console.log(this.state.inboxNames)
return(
<div className='inboxContainer'>
<div className='inbox'>
</div>
<div className='userProfile'>
<button onClick={() => this.clickHandler()}>Add Game</button>
<button>Available for Hosting</button>
</div>
</div>
)
}
}
const mapStateToProps = (state) => ({
position: state.rootReducer.position,
search:state.rootReducer.search,
markers:state.rootReducer.markers,
markerClicked:state.rootReducer.markerClicked,
user:state.rootReducer.user,
message:state.rootReducer.messages
});
const mapDispatchToProps = (dispatch) => ({
success: () => dispatch(push('/')),
locationFunction: (position) => dispatch({type:"LOCATION", lat:position.coords.latitude, long:position.coords.longitude}),
defineUser: (user) => dispatch({type:'USER', user:user})
});
Inbox = connect(mapStateToProps, mapDispatchToProps)(Inbox);
export default Inbox;
&#13;
以下是componentDidMount函数中console.log记录的内容。
in componentDidMount
{}
heytherefriend@gmail.com:
{key: "-Ksj1j2aKJyWD5q28Bhs", chat: Array(1)}
peter@gmail.com:
{key: "-KtI338W3l03wIYaOmFW", chat: Array(1)}
thegreekjester@gmail.com:
{key: "-KsesFczZbIO2wJxLKh5", chat: Array(1)}
__proto__:Object
&#13;