基本上,每当我在我的 handleDelete 函数中删除一个项目时,它都会返回主页,我想显示一条消息,说明您的产品已成功删除约 5 秒。
在我的 index.js 中,我首先将 message 设置为 false。并且在我的 ProductAttribute 中,每当我单击它时,设置的消息都会为真,并将在我的 UI 中的 Index.js/中显示该消息。
我的句柄删除功能
import React, { useState } from "react";
import { Header, Button, Modal } from "semantic-ui-react";
import axios from "axios";
import baseUrl from "../../utils/baseUrl";
import { useRouter } from "next/router";
function ProductAttributes({ description, _id }) {
const [modal, setModal] = useState(false);
const router = useRouter();
async function handleDelete() {
const url = `${baseUrl}/api/product`;
const payload = { params: { _id } };
await axios.delete(url, payload);
router.push("/");
setMessage(true);
setTimeout(function () {
setMessage(false);
}, 5000);
}
在我的 Index.js 中。我的 useState 中的 setMessage 没有从 ProductAttributes 文件中调用。import React, { useEffect, useState } from "react";
import axios from "axios";
import ProductList from "../components/Index/ProductList";
import baseUrl from "../utils/baseUrl";
import { Message, Container } from "semantic-ui-react";
function Home({ products }) {
const [message, setMessage] = useState(false);
return (
<>
<Container>
{message ? (
<Message
deleted
icon="checked"
color="red"
content=" Product Successfully Deleted"
/>
) : (
""
)}
</Container>
<ProductList products={products}></ProductList>
</>
);
}
如何使此 setMessage 在 ProductAttributes 中可调用?我在父子关系方面做得对吗,还是应该将子项中的 useState 带给父项?
最佳答案
您可以在 Home
中创建处理程序像这样的组件
const handleSetMessage = (message) => {
setMessage(message)
}
这个处理程序将负责更新 message
的值Home
中的状态零件。这个方法你可以把它作为 Prop 传递给 ProductList
也将其传递给 ProductAttribute
的组件.这将迫使您将 Prop 传递到您需要调用该方法的 APP 中的最低级别。或者您可以利用 Context API 将允许您访问该方法,而无需将其作为 Prop 传递。
const MessageContext = React.createContext("");
在 Home
您像这样使用该上下文的组件function Home () {
const [message, setMessage] = useState('');
const handleSetMessage = () => {
setMessage(true)
}
return <MessageContext.Provider> value={{setMessage: handleSetMessage}}>
// The code which render the component child goes here.
</MessageContext.Provider>
}
之后在您的 ProductAttribute
您访问的组件 setMessage
像这样的功能import React, { useContext} from 'react';
const ProductAttribute = (props) => {
const { setMessage } = useContext(MessageContext);
const handleDelete = async () => {
// Here you call the setMessage function which will update state in the `Home` Component
setMessage();
}
return <div>
</div>
}
关于javascript - 如何从另一个页面调用 useState?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62990652/