gpt4 book ai didi

javascript - 使用 ReduxReducer 修改嵌套状态

转载 作者:行者123 更新时间:2023-12-02 22:48:23 26 4
gpt4 key购买 nike

我遇到了一个让我大吃一惊的问题。我正在使用 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;

问题是,当我将状态 Prop 传递给演示组件时,通知对象为空

我的演示组件如下所示

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 中,我尝试打印新状态。我成功得到了这个:enter image description here

但是,无论如何,在我的演示组件中,我得到了一个空对象

最佳答案

我认为调度调用尚未触发。尝试执行下面的代码

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 是不安全的(根据 ReactJS 当前文档)。将来避免使用此生命周期。

关于javascript - 使用 ReduxReducer 修改嵌套状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58287622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com