TypeScript项目中getServerSideProps无法向主组件传值的解决方法咨询
修复Next.js中getServerSideProps向SelectArayeshgah组件传递数据的问题
问题分析
你的代码存在两个核心问题导致数据无法正确传递:
- Props结构不匹配:
getServerSideProps要求返回的props是一个对象,但你直接返回了数组;同时组件的props类型定义为IArayeshgah[],和实际传递的结构不兼容。 - Redux状态未初始化:组件依赖Redux的
arayeshgahInfos渲染列表,但没有将getServerSideProps传递的props数据同步到Redux状态中。
修复步骤及代码
- 修正Props类型定义:创建包含数组的接口,明确组件接收的props结构
- 调整getServerSideProps返回结构:将数组包装在对象的指定键下
- 同步Props到Redux:在组件挂载时将props数据dispatch到Redux初始化状态
修改后的完整代码:
import Modal from "@/components/modal"; import React from "react"; import Check from "../components/check"; import { setArayeshgahInfo } from "../redux/slice"; import { useDispatch } from "react-redux"; import { useAppSelector, updatesetArayeshgahStatus } from "../redux/slice"; import { GetServerSideProps } from "next"; export interface IArayeshgah { id: string; title: string; check?: boolean | undefined; } // 定义组件接收的props接口,包含arayeshgahs数组 interface SelectArayeshgahProps { arayeshgahs: IArayeshgah[]; } function SelectArayeshgah({ arayeshgahs }: SelectArayeshgahProps) { const dispatch = useDispatch(); console.log("传递的props数据:", arayeshgahs); // 组件挂载时将props数据同步到Redux React.useEffect(() => { if (arayeshgahs.length > 0) { dispatch(setArayeshgahInfo(arayeshgahs)); } }, [arayeshgahs, dispatch]); const arayeshgahInfos = useAppSelector((state) => state.arayeshgahs); // 需匹配你的Redux slice中的实际字段 const toggle_Arayeshgah_State = ({ id }: { id: string }) => { dispatch(updatesetArayeshgahStatus({ id })); }; const ArayeshgahItems = () => { return ( <div className="flex mt-4"> {arayeshgahInfos?.map((item) => ( <div key={item.id} // 必须添加key属性避免React警告 className="w-52 rounded-xl shadow-sm bg-gray-300 border text-sm h-10 flex justify-between pr-2 pl-2 items-center" onClick={() => toggle_Arayeshgah_State({ id: item.id })} > <span>{item.title}</span> <Check isCheck={item.check ?? false} size="sm" /> </div> ))} </div> ); }; return ( <Modal callback={() => {}} denyText="انصراف" headerText="انتخاب آرایشگاه" acceptText="تایید" bodyText="پس از انتخاب آرایشگاه مورد نظر بر روی دکمه تایید بزنید" > <ArayeshgahItems /> </Modal> ); } export const getServerSideProps: GetServerSideProps = async (context) => { // 将数组包装在对象的arayeshgahs键下,符合Next.js的props传递规则 return { props: { arayeshgahs: [{ id: "DKLGJDFKLHJDFLK", title: "تک چهره", check: false }] } }; }; export default SelectArayeshgah;
额外注意事项
- 确保你的Redux slice中的
setArayeshgahInforeducer能够正确接收并存储数组数据 - 渲染列表时必须添加
key属性,避免React控制台警告 - 使用
item.check ?? false处理可选属性的默认值,避免undefined引发的渲染错误
内容的提问来源于stack exchange,提问作者Amin Soraya
相关产品推荐
相关产品推荐

