提问人:Muhammed Aboo_Anas 提问时间:11/6/2023 更新时间:11/6/2023 访问量:37
使用服务器操作在 Next.js 13 中将状态从子组件提升到父组件
Lifting up state from Child to Parent Component in Next.js 13 using server actions
问:
我正在做一个项目,点击四个不同的选项卡显示不同的信息。我正在尝试将状态从子客户端组件提升到父服务器组件,但我不断收到错误。例如,单击“所有课程”选项卡应将客户端组件的状态设置为“全部”,并使其可在父组件中访问。
子组件(客户端组件):
export default function CategoryTab(update){
const [category, setCategory] = useState("all")
const handleClick = (category) => {
setCategory(category)
let update = category
return update
}
return (
<React.Fragment>
<div className={styles.category_tab}>
<ul>
<li onClick={() => handleClick("all")}>All Courses</li>
<li onClick={() => handleClick("doctorate")}>Doctorate Courses</li>
</ul>
<ul>
<li onClick={() => handleClick("diploma")}>Diploma Courses</li>
<li onClick={() => handleClick("certificate")}>Certificate Courses</li>
</ul>
</div>
</React.Fragment>
)
}
父组件(服务器组件):
export default function CourseList(){
const getCategory = async (category) => {
"use server"
let response = await category
console.log(response)
return response
}
return (
<React.Fragment>
<section className={styles.courses_container}>
<h1>programmes</h1>
<h2>Below are the different available programmes at XYZ</h2>
<CategoryTab update = {getCategory}/> //CHILD COMPONENT
{category==="all" && <p>all</p>}
{category==="doctorate" && <p>doctorate</p>}
{category==="all" && <p>all</p>}
</section>
</React.Fragment>
)
}
下面是下一个.js配置文件:
const nextConfig = {
experimental: {
serverActions: true,
},
}
答:
1赞
alpha_N1618
11/6/2023
#1
您实际上是将函数传递给子组件,并且应该向其传递一个值,而不是
let update = category
不管这是
什么 这里是一个类型脚本的例子:
父组件
type MyFunctionType = (parameter: string) => void;
export default async function Parent() {
const myFunction: MyFunctionType = async (parameter) => {
"use server";
console.log(`Received parameter: ${parameter}`);
};
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<Child myFunction={myFunction} />
</main>
)
子组件“客户端”
"use client"
type ChildProps = {
myFunction: MyFunctionType;
};
const Child = (props: ChildProps) => {
const { myFunction } = props;
return (
<button onClick={() => myFunction("your state")} >
CLICK
</button>
);
这将向 myFunction 提供数据并登录您的终端。
评论