我遇到了一个问题,它使我全神贯注。 我正在使用React和Redux开发Web应用程序,我的应用程序使用通过Firebase实现的通知系统。 每个通知的结构如下:
var notification = {
from_user:{
name: 'John',
surname: 'Doe'
},
payload:{
message:'Lorem ipsum ...'
}
seen:false,
timestamp:1569883567
}
获取后,通知将通过以下方式发送到notificationReducer:
dispatch({type:'FETCH_NOTIFICATION_OK',payload:notification})
到目前为止,一切正常。
我的notificationReducer的结构如下:
const INITIAL_STATE = {
loading:false,
notification:{}
}
const notificationReducer = (state=INITIAL_STATE,action)=>{
switch(action.type){
case 'FETCHING_NOTIFICATION':
return {...state,loading:true}
case 'FETCH_NOTIFICATION_OK':
return {...state,loading:false,notification:action.payload} // I THINK PROBLEM IS HERE
default:
return state
}
}
export default notificationReducer;
问题在于,当我将状态道具传递给演示组件时,通知对象为空
我的演示组件报告如下
import React from 'react';
import {getNotification} from '../actions/actioncreators';
import {connect} from 'react-redux';
class NotificationDetail extends React.Component {
componentWillMount(){
this.props.fetch_notification('9028aff78d78x7hfk');
console.log(this.props.notification) // IT PRINTS: {}
}
render(){
return(
<div>
'TODO'
</div>
)
}
}
const mapStateToProps = state =>{
return {
is_loading:state.notificationReducer.loading,
notification:state.notificationReducer.notification
}
}
const mapDispatchToProps = dispatch =>{
return {
fetch_notification: (id_notification)=>dispatch(getNotification(id_notification))
}
}
export default connect(mapStateToProps,mapDispatchToProps)(NotificationDetail)
有什么建议吗?
编辑:在我的reducer中,我试图打印新状态。我成功获得了这个:
但是,无论如何,我在演示组件中有一个空对象
答案 0 :(得分:1)
我认为调度电话尚未触发。尝试执行以下
componentDidMount() {
this.props.fetch_notification();
}
render() {
console.log(this.props.notification); // It should print an output here if your xhr/ajax/axios call is correct
}
此外,使用componentWillMount是UNSAFE(根据ReactJS当前文档)。避免将来使用此生命周期。