【问题标题】:How to update status of Parent sate using functional component react如何使用功能组件反应更新父状态的状态
【发布时间】:2021-01-24 21:38:39
【问题描述】:

我在我的代码中使用了 2 个 useState。当第二个 useSate 状态为真时,我希望将第一个 useState 状态设为假。

我可以使用类组件而不是函数组件来实现它。

类组件代码

 class App extends React.Component {
 state = { visible: false, childrenDrawer: false };

showDrawer = () => {
this.setState({
  visible: true,
});
};

onClose = () => {
this.setState({
  visible: false,
});
};

showChildrenDrawer = () => {
this.setState({
  childrenDrawer: true,
  visible: false, //**this make 1st state status false when 2nd state is true**
});
};

onChildrenDrawerClose = () => {
this.setState({
  childrenDrawer: false,
});
};

如何在功能组件中实现这一点,请指导

 const [visible, setVisible] = useState(false);
 const [hideAuto, setAuto]= useState(false);

 const showDrawer = () => {
 setVisible(true);
 };

const onClose = () => {
setVisible(false);
};

const Quality=()=>{
setAuto(true);
}

const Selection = () => {
setVisible(false);
};

【问题讨论】:

    标签: reactjs react-hooks next.js


    【解决方案1】:

    您可以使用 React 钩子在函数组件中初始化和更新状态,就像在您的类中一样。

    在您的功能组件中,为什么要使用两个单独的挂钩?为什么不像你在课堂上那样跟踪状态,即。使用单个对象。例如:

    let [myState, updateMyState] = useState({ visible: false, childrenDrawer: false });
    

    然后更新状态:

    updateMyState(...myState, visible: true) // show drawer for example
    

    【讨论】:

      【解决方案2】:

      这个简单的设置怎么样,你将改变父状态的函数作为道具传递给子组件:

      const parentDrawer = () => {
          const [parentState, setParentState] = useState(true);
          const onChildClose = () => {
              setParentState(false)
          }
          return <childDrawer onChildClose={onChildClose} />
      }
      
      const childDrawer = ({ onChildClose }) => {
          const onChildInteraction = () => {
              onChildClose()
          }
          return (...)
      }
      

      这涵盖了父级渲染/返回子级的情况。如果您将它们分开,也许可以查看上下文。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        • 1970-01-01
        • 2022-06-27
        • 2022-10-06
        相关资源
        最近更新 更多