【问题标题】:Passing useState Hook into another function on React将 useState Hook 传递给 React 上的另一个函数
【发布时间】:2021-06-04 20:09:00
【问题描述】:

我想在 useState 钩子中传递一个布尔值,该钩子在两个函数之间单击时打开和关闭模式。但是,我不断收到此错误消息:Cannot destructure property 'setOpenModal' of 'props' as it is undefined.

Main.js

import React, { useState, useEffect } from "react";    
import * as Materials from "../components/Materials"; // <- Material.js

const Main = () => {

    const [openModal, setOpenModal] = useState(false); //<- Opens (True) and Closes (False) Modal
    const { MaterialContainer } = Materials.MaterialTable(); // <-Calling Function Under MaterialTable

return (

    <MaterialContainer 
      openModal={openModal}
      setOpenModal={setOpenModal}
    /> 
    // This is how I am passing in Open/Close useState.
}

Material.js

export const MaterialTable = (props) => {

  const { openModal, setOpenModal } = props; // <- Pointed in Error Message.

  const openMaterialModal = (item) => {
    console.log("Button Clicked");
    setOpenModal(true); // <- Where I am passing in a true statement.
  };

  const MaterialContainer = () => (
    <>
        <Table>Stuff</Table>
    </>
  );
  return {
    MaterialContainer
  }
}

提前致谢。

【问题讨论】:

  • 您能否为Main.js 提供更全面的代码示例?不清楚你是否有一个正确的 React 组件。
  • @DrewReese 当然!
  • 这看起来很奇怪。除了 MaterialTable 的内部,您无法到达 MaterialContainer

标签: reactjs function react-hooks undefined use-state


【解决方案1】:

MaterialTable 组件从 React 的角度来看是完全错误的,尽管是有效的 JavaScript。它只是一个普通函数,定义了几个常量,然后什么也不返回。 (好吧,在最初的问题中它什么也没返回。现在它返回一个对象。)

当你调用那个函数时,你确实没有向它传递任何东西:

const { MaterialContainer } = Materials.MaterialTable();

所以props 将是undefined

使MaterialTable 本身成为一个 React 组件:

export const MaterialTable = (props) => {

    // destructure the props passed to the component
    const { openModal, setOpenModal } = props;

    // a function I assume you plan to use in the JSX below later?
    const openMaterialModal = (item) => {
        console.log("Button Clicked");
        setOpenModal(true);
    };

    // the rendering of the component
    return (
        <>
            <Table>Stuff</Table>
        </>
    );
}

然后只需导入并使用该组件,而无需尝试从中解构任何内容或手动调用它:

import React, { useState, useEffect } from "react";
// import the component
import { MaterialTable } from "../components/Materials";

const Main = () => {

    // use the state hook
    const [openModal, setOpenModal] = useState(false);

    // render the component, passing props
    return (
        <MaterialTable
          openModal={openModal}
          setOpenModal={setOpenModal}
        />
    );
}

【讨论】:

  • 非常感谢!它起作用了,但它破坏了其他东西。 XD 如果一个 useState "const [value, setValue]" 存在并且正在 Material.js 中使用,并且希望在 Main.js 中也使用 "setValue",你会怎么做?
  • @JaeWon:简单来说,这听起来像是范围错误。如果父组件需要了解给定状态,则该状态应在该父组件处或之上进行管理,而不是在子组件中。但是,如果我们假设您拥有的结构需要这样,那么您可以做的是让父组件将一个函数传递给子组件的 props 以在给定事件中调用。子组件仍然可以保持该状态,但将更新的值传递给父组件的回调函数。不过,这可能会很快变得非常笨拙。
猜你喜欢
  • 1970-01-01
  • 2019-08-11
  • 2020-08-04
  • 2019-07-25
  • 1970-01-01
  • 2012-09-25
  • 2020-10-03
相关资源
最近更新 更多