【问题标题】:How to call useState from another Page?如何从另一个页面调用 useState?
【发布时间】:2020-11-09 10:12:13
【问题描述】:

基本上,每当我在 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 带给父项?

【问题讨论】:

  • 请将代码发布为文本而不是屏幕截图。
  • 我会编辑它。等等
  • @Code-Apprentice 它已经被编辑过了。你有答案吗?
  • @BloodyLogic 我已经对其进行了编辑并将其转换为代码。

标签: javascript reactjs react-router use-state


【解决方案1】:

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

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

这是一个例子:

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

然后在 ChildComponent..

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

【讨论】:

  • 我该怎么做?
  • 我不明白。我将如何从 Index.js 调用 ProductAttributes ?
  • 所以我将 index.js 导入到 ProductAttributes 中?
【解决方案2】:

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

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

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

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

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

【讨论】:

  • 发生了什么?为什么没了?
【解决方案3】:

显示消息后,等待 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);
}

【讨论】:

  • 它应该首先路由到索引 router.push("/") 然后显示消息。并且 setMessage 说它不是一个函数。如何将 setMessage 从 Index.js 调用到 ProductAttributes.js? .
  • 你应该将setMessage 的props 传递给ProductAttributes 组件,这样它就可以工作了!
  • function ProductAttributes({ description, _id, setMessage }) 我通过了它,它说 setMessage 不是函数
  • github.com/GrizzlyBear-Michaelangelo/Ecommerce.git 就是这样。抱歉回复晚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2014-09-04
  • 1970-01-01
相关资源
最近更新 更多