javascript - 如何从另一个页面调用 useState?

标签 javascript reactjs react-router use-state

基本上,每当我在我的 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/

相关文章:

javascript - 在 React 中更新 d3 元素?

java - 无法找到 org.gradle.initialization.DefaultSettings 类型的设置 ‘MyApplicationExample' 参数的方法存储库 ()

javascript - React this.props 在状态事件中未定义?

javascript - 适用于 Node 的 Azure SDK - key 保管库管理 - CORS 预检 : server responded with a status of 400 (Bad Request)

javascript - 如果react-router-dom不匹配任何路由,则页面重新加载

reactjs - 没有服务器的 react 应用程序

javascript - Bootstrap 下拉元素未正确对齐

javascript - 如何使用 if hasClass 条件禁用 jQuery mouseleave 事件?//悬停动画

javascript - Rails 客户端验证——禁用提交直到验证通过

javascript - 仅在一个页面上关闭导航栏图标