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

IT技术 javascript reactjs react-router use-state
2021-04-29 20:05:25

基本上,每当我在 handleDelete 函数中删除一个项目时,它都会返回到主页,我想显示一条消息,说明您的产品已成功删除约 5 秒钟。

在我的 index.js 中,我首先将 message 设置为 false。并且在我的 ProductAttribute 中,每当我单击它时,设置的消息将为 true,并将在我的 UI 中的 Index.js/ 中显示该消息。

我的 handleDelete 函数

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>
        </>
    );
}

如何在 ProductAttributes 中使这个 setMessagebe 可调用?我在父子关系中做得对吗,还是应该将子项中的 useState 带给父项?

3个回答

如何在 ProductAttributes 中使这个 setMessagebe 可调用?

一个好的做法是创建一个处理程序函数,该函数委托给 setState 函数并将此函数的引用作为props传递给 ProductAttributes。

这是一个例子:

const [counter, setCounter] = useState(0);
const handleIncrementCounter = () => setCounter(counter + 1);
<ChildComponent handleIncrementCounter ={handleIncrementCounter }/>

然后在 ChildComponent..

function ChildComponent(props) {
   return (
      <button onClick={props.handleIncrementCounter}/>
   );
}

您可以Home像这样组件中创建处理程序

const handleSetMessage = (message) => {
    setMessage(message)
}

此处理程序将负责更新组件中message状态Home并且这个方法你可以将它作为props传递给ProductList组件,组件也会将它传递给ProductAttribute. 这将迫使您将 props 传递到您需要调用该方法的 APP 中的最低级别。

或者您可以利用Context API,它允许您访问该方法,而无需将其作为props传递。

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>
}

向您显示消息后,等待 5 秒关闭消息并重定向回主目录。只需将route.push('/')内部放置,setTimeout这样它就会等待 5 秒被重定向。

async function handleDelete() {
    const url = `${baseUrl}/api/product`;
    const payload = { params: { _id } };
    await axios.delete(url, payload);
    setMessage(true);
    setTimeout(function () {
        router.push("/");
        setMessage(false);
    }, 5000);
}