【问题标题】:Get state variable from child component using React 16.8^ coding style使用 React 16.8^ 编码风格从子组件获取状态变量
【发布时间】:2020-10-28 08:03:16
【问题描述】:

这个问题已经被问过了,但我找不到使用钩子的答案。

我需要读取页面中调用组件的状态变量。

MyPage.js

import React from "react"
import MyComponent from "../components/MyComponent"

export default function MyPage() {
  console.log("Read stateVariable value here " + stateVariable) // produce error
  return (
      <MyComponent />
  )
}

MyComponent.js

import React, { useState } from "react"
import ExternalModule from "ExternalModule"

export default function MyComponent() {

const [stateVariable, setStateVariable] = useState(0))

 return (
    <div
      onClick={setStateVariable(stateVariable + 1)}
    >CLICK HERE
      <ExternalModule
        stateVariable={stateVariable}
      />
    </div>
  )

如何在 MyPage 中 console.log stateVariable

【问题讨论】:

  • 你问的是Lifting State Up吗?
  • 可能是,如题我在找React-with-hooks的解释,因为不熟悉Class/Constructor/this.state,官方用的文档(您的链接)。 AFAIK 提升状态不是使用反应钩子处理状态管理的常用方法,但我也可能错了
  • 提升状态是一种设计模式,反应钩子是一个实现细节。他们彼此没有任何关系。将const [stateVariable, setStateVariable] = useState(0); 移动到MyPage 并将stateVariablesetStateVariable 作为道具传递给MyComponent 以呈现并附加为onClick 回调。

标签: reactjs react-hooks state state-management


【解决方案1】:

当您有多个组件需要访问一个状态时,您希望该状态由树中最高的组件拥有并向下传递给其余组件。

useState 调用上移至MyPage,并将stateVariablesetStateVariable 作为道具传递给MyComponent

export default function MyPage() {

    const [stateVariable, setStateVariable] = useState(0)

    console.log("Read stateVariable value here " + stateVariable)

    return (
        <MyComponent 
            stateVariable={stateVariable} 
            setStateVariable={setStateVariable} 
        />
    )
}

export default function MyComponent({ stateVariable, setStateVariable]) {
    return (
        <div
            onClick={setStateVariable(stateVariable + 1)}
        >CLICK HERE
            <ExternalModule
                stateVariable={stateVariable}
            />
        </div>
    )
}

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 2021-02-28
    相关资源
    最近更新 更多