异步映射状态到props返回undefined,而normal返回值

时间:2018-10-24 01:46:33

标签: reactjs redux

import React from 'react';
import {connect} from 'react-redux';
import fetch from '../firebase/retrive_firebase';
import { database } from "../firebase/firebase";
import Filter_product_list from './product_list_filter';
import get_visible_products from '../selectors/get_visible_products';
class ViewProduct extends React.Component
{

    render()
    { 
        console.log(this.props.a);
        return(
            <div>
               <Filter_product_list />
            </div>   
        )
    }
}

const map_state_to_props=async(state)=>
{
    let firebase_product={}
 
     const promise=await fetch().then((response)=>{
        console.log('promise resolved');
        
        firebase_product=response
          firebase_product.map((entry)=>{console.log(entry)});
           return firebase_product
         //const filtered_products=await get_visible_products(firebase_product,state.filters);
         //console.log("filtered products",filtered_products);
    }).catch((err)=>{

    })
    console.log("what got retured from promise",promise)
     const filtered_products=get_visible_products(promise,state.filters);
    console.log("filtered products",filtered_products)
         return{
           //filtered_products,
           a:15,
        }
    // console.log("type of fetch",typeof(firebase_product))
    // firebase_product.map((product2)=>{console.log("products ",product2)});
    // console.log("product returned from fetch",firebase_product);
    // const product=get_visible_products(firebase_product,state.filters)
    // console.log("product returned from visible expenses",product);
};

export default connect(map_state_to_props,{})(ViewProduct);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

我正在使用props的异步映射状态,并且在我使用redux连接到的上述组件中返回undefined。我将map state的值作为对象的对象返回给props,其中键是a并且我得到了在控制台中从this.props.a

中未定义

1 个答案:

答案 0 :(得分:0)

mapStateToProps不能异步。例如,您应该使用适当的中间件作为redux-saga执行异步操作。基本上,您是在中间件中执行异步操作,然后通过reducer将其结果设置到您的商店中,然后使用mapStateToProps将其传播到您的组件中。