组件重新渲染后,无法使用useState挂钩更新变量

时间:2019-03-20 19:19:10

标签: reactjs redux

我希望在用户成功登录或发生错误时显示一个快餐栏。 MyComponent.jsx:

import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import SnackBar from '../../components/SnackBar';
import SignInForm from './SignInForm';

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(!!variant);

    const handleClose = () => {
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

SingInContainer.propTypes = {
    variant: PropTypes.string.isRequired,
    message: PropTypes.string.isRequired
}

const mapStateToProps = (state) => {
    const {variant, message } = state.snackBar;

    return {
        variant,
        message
    }
}

export default connect(mapStateToProps)(SingInContainer);

open道具始终设置为false,但是variant HOC重新渲染了组件后,connect被更新。我没有发现我的错误是什么?

1 个答案:

答案 0 :(得分:1)

useState的参数仅在初始更新时使用一次,如果要执行更新以更新变量prop的状态,则可以使用useEffect挂钩

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(!!variant);
    useEffect(() => {
       setSnackBarState(!!variant);
    }, [variant])
    const handleClose = () => {
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}