Reducer returns 有效负载正确但组件将其接收为未定义

Reducer returns payload correctly but the component receives it as undefined

我正在实现一个从 firebase 获取一些数据的应用程序。 firebase 数据库不需要身份验证,我已经更改了 public 访问规则。

但是,我有一个使用 firebase 键从数据库中获取特定行的操作:

行动

export function fetchClient(id) {
  return (dispatch) => {
     database.ref(`/clients/${id}`)
        .on('value', snapshot => {
            console.log(snapshot.val());
        dispatch({
            type: FETCH_CLIENT,
            payload: snapshot.val()
        });
     }); 
  };
} 

Console.log表示数据已经取回成功

我的 reducer 也 returns 有效负载成功:

减速机

const INITIAL_STATE = {}

export default function (state = INITIAL_STATE, action) {
 switch(action.type){
    case FETCH_CLIENTS:
        return action.payload;
    case FETCH_CLIENT:
        console.log(action.payload );
        return { ...state, [action.payload.id]: action.payload };
    case CREATE_CLIENT:
        return action.payload;
    default: 
        return state;
  }
}

然而,当我从上一页向它 link 时,该组件收到未定义的有效载荷,并且当我刷新页面时显然为空。

分量

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchClient } from '../actions';
import { Link } from 'react-router-dom';

class ClientShow extends Component {

componentDidMount() {
  const { id } = this.props.match.params;
  console.log(this.props);
  this.props.fetchClient(id);
}
render(){
  const { myClient } = this.props;
  if (!myClient) {
    return (
        <div>
            <Link className="btn btn-danger" to="/" >Home</Link>
            <div>Loading...</div>
        </div>
    );
  }
  return (
    <div>
        <Link to="/"  className="btn btn-primary" >Home</Link>
        <h2>{myClient.name}</h2>
        <h4>The client is loaded... but undefined</h4>
    </div>
  ); 
 }
}

function mapStateToProps({ clients }, ownProps) {
  //console.log(ownProps.match.params.id);    
  return { myClient: clients[ownProps.match.params.id] };
}

export default connect(mapStateToProps, { fetchClient })(ClientShow);

URL 中的密钥显示正确,并且从 mapStateToProps 中的 console.log 我收到了正确的参数。

控制台日志

客户console.log表单client_show组件

所以,我终于解决了这里的问题。

基本上,我没有将动作中的 firebase 键发送到 reducer,而是希望在 action.payload.id 中有 id。

我现在在传递 firebase 密钥的对象中添加了一个新元素:

export function fetchClient(id) {
  return (dispatch) => {
     database.ref(`/clients/${id}`)
        .on('value', snapshot => {
            console.log(snapshot.val());
        dispatch({
            type: FETCH_CLIENT,
            key: id, // Adding the Firebase KEY here
            payload: snapshot.val()
        });
     }); 
  };
} 

然后,在我的减速器中:

case FETCH_CLIENT:
  return { ...state, [action.key]: action.payload };