如何从另一个页面调用 useState? [英] How to call useState from another Page?

查看:39
本文介绍了如何从另一个页面调用 useState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,每当我在 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";从axios"导入 axios;从../../utils/baseUrl"导入 baseUrl;import { useRouter } from next/router";功能产品属性({描述,_id}){const [modal, setModal] = useState(false);const 路由器 = useRouter();异步函数 handleDelete() {const url = `${baseUrl}/api/product`;const 有效载荷 = { params: { _id } };等待 axios.delete(网址,有效载荷);router.push("/");设置消息(真);设置超时(函数(){设置消息(假);}, 5000);}

在我的 Index.js 中.我的 useState 中的 setMessage 没有从 ProductAttributes 文件中调用.

import React, { useEffect, useState } from "react";从axios"导入 axios;从../components/Index/ProductList"导入产品列表;从../utils/baseUrl"导入 baseUrl;从semantic-ui-react"导入{消息,容器};功能首页({产品}){const [message, setMessage] = useState(false);返回 (<><容器>{信息 ?(<消息已删除图标=已检查"颜色=红色"内容="产品已成功删除"/>) : (")}</容器><ProductList products={products}></ProductList></>);}

如何使这个 setMessage 在 ProductAttributes 中可调用?我对父子关系的处理是否正确,还是应该将子项中的 useState 带给父项?

解决方案

你可以像这样在 Home 组件中创建一个处理程序

const handleSetMessage = (message) =>{设置消息(消息)}

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

或者您可以利用 Context API 来访问该 API方法而不将其作为道具传递.

const MessageContext = React.createContext("");

Home 组件中,您可以像这样使用该上下文

function Home() {const [message, setMessage] = useState('');const handleSetMessage = () =>{设置消息(真)}返回 value={{setMessage: handleSetMessage}}>//渲染子组件的代码放在这里.</MessageContext.Provider>}

之后,在您的 ProductAttribute 组件中,您可以像这样访问 setMessage 函数

import React, { useContext} from 'react';const ProductAttribute = (props) =>{const { setMessage } = useContext(MessageContext);const handleDelete = async() =>{//在这里调用 setMessage 函数,该函数将更新 `Home` 组件中的状态设置消息();}返回 

}

Bascially whenever I deleted an item in my handleDelete function it would route back to the homePage and I wanted to display a message that says your product succesully deleted for about 5 seconds.

In my index.js I first set message to false. and inside my ProductAttribute whenever I click it the set message will be true and will show the message in Index.js/ in my UI.

my handleDelete function

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

while in my Index.js. The setMessage in my useState isn't getting called from ProductAttributes file.

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

How can I make this setMessagebe callable in ProductAttributes? am I doing it right with the Parent to Child Relation or should I bring the useState in the child to parent?

解决方案

You can create an handler in the Home Component like this

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

this handler will be responsible of updating the value of message state in the Home component. and this methode you can pass it as props to ProductList component which will also pass it down to ProductAttribute. This will force you to pass props till the lowest level in your APP where you need to call that method.

Or you can take advantage of Context API which will allow you to have access to that method without passing it down as props.

const MessageContext = React.createContext("");

And in the Home component you use that Context like this

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

After that in your ProductAttribute Component you access to that setMessage function like this

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

这篇关于如何从另一个页面调用 useState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆