如何从Redux Store取数?List组件this.props未定义求助
问题分析与修复方案
我仔细看了你提供的示例代码,发现导致List组件里this.props为undefined的问题主要有两处,咱们一步步来解决:
1. 未将组件与Redux Store关联
你的List组件目前没有和Redux Store建立连接,所以根本无法获取到store里的数据。需要用Redux的connect函数把store中的state映射到组件props上:
首先在List.js顶部导入connect:
import { connect } from 'react-redux';
然后定义一个mapStateToProps函数,把store里的crypto数据映射为组件的props:
const mapStateToProps = (state) => { return { crypto: state.crypto }; };
最后修改组件的导出语句,用connect包裹原始的List组件:
export default connect(mapStateToProps)(List);
2. 构造函数未正确接收props
如果组件使用了构造函数,必须调用super(props),否则在构造函数内部this.props会是undefined。修改你的构造函数:
constructor(props) { super(props); // 这一步是关键,不能省略 // 你的其他初始化逻辑 }
3. 可选但推荐:处理异步数据加载状态
因为API请求是异步的,初始时crypto数据可能还没返回,所以在render里最好先做判断,避免出现渲染报错:
render() { const { crypto } = this.props; // 数据未加载完成时显示加载提示 if (!crypto || crypto.length === 0) { return <div>Loading crypto data...</div>; } // 数据加载完成后渲染列表 return ( <ul> {crypto.map(item => ( <li key={item.id}>{item.name}: {item.price_usd}</li> ))} </ul> ); }
做完这些修改后,List组件就能正常获取到Redux Store中的数据,this.props也不会再是undefined了。
内容的提问来源于stack exchange,提问作者Stave
相关产品推荐
相关产品推荐

