类型不兼容问题:HomeProps无法赋值给SetStateAction<ActivityProps[] | null>
解决类型不匹配问题:将HomeProps数据传入Activity状态
问题根源
你遇到的类型错误有两个核心原因:
activity状态定义为数组类型(ActivityProps[] | null),但你传入的是单个HomeProps对象,类型不匹配;HomeProps包含ActivityProps没有的字段(ath、atl、symbol),直接赋值会触发类型检查报错。
根据你的实际需求,提供两种解决方案:
方案一:Activity组件仅需单个选中项
如果Activity只展示当前选中的加密货币数据,修改状态类型为单个对象,同时提取ActivityProps需要的字段:
步骤1:修改状态定义
// 把数组类型改为单个ActivityProps对象或null const [activity, setActivity] = useState<ActivityProps | null>(null);
步骤2:转换数据并更新状态
在onSelectItem回调中,从crypto提取ActivityProps所需字段:
<Coin key={crypto.id} name={crypto.name} image={crypto.image} current_price={crypto.current_price} id={crypto.id} onSelectItem={() => { // 解构提取需要的字段,自动匹配ActivityProps类型 const { current_price, high_24h, id, image, low_24h, name, price_change_24h, price_change_percentage_24h } = crypto; setActivity({ current_price, high_24h, id, image, low_24h, name, price_change_24h, price_change_percentage_24h }); }} />
方案二:Activity组件需要维护选中历史(数组)
如果需要保存多个选中的加密货币记录,保持数组状态类型,将单个HomeProps转换为ActivityProps后添加到数组:
步骤1:保持原状态定义
const [activity, setActivity] = useState<ActivityProps[] | null>(null);
步骤2:追加数据到数组
<Coin key={crypto.id} name={crypto.name} image={crypto.image} current_price={crypto.current_price} id={crypto.id} onSelectItem={() => { const { current_price, high_24h, id, image, low_24h, name, price_change_24h, price_change_percentage_24h } = crypto; const newActivityItem: ActivityProps = { current_price, high_24h, id, image, low_24h, name, price_change_24h, price_change_percentage_24h }; // 更新数组:已有数据则追加,无数据则创建新数组 setActivity(prev => prev ? [...prev, newActivityItem] : [newActivityItem]); }} />
额外说明
- 不建议直接使用类型断言(如
crypto as ActivityProps),因为HomeProps包含多余字段,可能隐藏潜在类型问题; - 解构提取字段的方式更安全,能明确控制传入
Activity的数据范围,符合TypeScript的类型安全原则。
内容的提问来源于stack exchange,提问作者Elijah McCoy
相关产品推荐
相关产品推荐

