如何设置组件上的状态?

时间:2020-10-22 12:31:19

标签: reactjs

在reactjs上,如何再次设置Notify组件上的状态?

import React, { useState } from 'react'

const NotificationError = (props) => {

    const [notify, setNotify] = useState(false);

    // if (props.message === "") {
    //     props.message = "Some Error"
    // }

    // if (props.message !== "") {
    //     setNotify(false)
    // }

    // if (props) {
    //     const [notify] = useState(true)
    // }

    console.log("notify.state:", props)

    const closeNotification = (e) => {
        console.log("Should be closing notification")
        setNotify(e)
    }

    return (
        <div className="notification is-danger" style={notify ? {display: 'none'} : {display: 'block'}}>
            <button className="delete" onClick={() => closeNotification(true)}></button>
            Error: {props.message}
        </div>
    )
}

export default NotificationError

如果我使用以下内容:

if (props) {
    const [notify] = useState(true)
}

我得到了错误,

第17:26行:有条件地调用React Hook的“ useState”。在每个组件渲染React-hooks / rules-of-hooks中,必须以完全相同的顺序调用React Hooks

如果我使用以下内容

if (props.message !== "") {
        setNotify(true)
    }

它抛出以下内容...

错误:重新渲染次数过多。 React将渲染数量限制为 防止无限循环。

简而言之,我不理解这一点。你能帮忙吗? :(

2 个答案:

答案 0 :(得分:0)

将逻辑重写为:

const NotificationError = (props) => {
  const [notify, setNotify] = useState(false);

  useEffect(() => {
    if (props.message === "") {
      props.setMessage('Some Error');
    }
    setNotify(false);
  }, [props.message]);

  return (
    <div
      className="notification is-danger"
      style={notify ? { display: "none" } : { display: "block" }}
    >
      <button className="delete" onClick={() => setNotify(true)}></button>
      Error: {props.message}
    </div>
  );
};

道具是不可变的,因此,如果您想更改一条消息,则应传递一个回调。 另外,请阅读有关Rules of Hooks的内容。

答案 1 :(得分:0)

在这种情况下,请使用useEffect钩子。它的作用类似于类组件中的componentDidMountcomponentDidUpdate。这意味着您作为useEffect钩子的第一个参数传递的函数会在组件安装时第一次触发,然后每次您更改数组的任何元素作为第二个参数传递时都会触发。

这是代码示例:

const NotificationError = (props) => {
    const [notify, setNotify] = useState(false);
    
    useEffect(() => {
        if(props.message != '') {
           setNotify(false);
        }
    }, [props.message])

    const closeNotification = (e) => {
        console.log("Should be closing notification")
        setNotify(e)
    }

    return (
        <div className="notification is-danger" style={notify ? {display: 'none'} : {display: 'block'}}>
            <button className="delete" onClick={() => closeNotification(true)}></button>
            Error: {props.message}
        </div>
    )
}
相关问题