【问题标题】:difference between state separately and together in react jsreact js中分别状态和一起状态的区别
【发布时间】:2021-06-24 13:58:24
【问题描述】:

我把状态写成

 const [state,setState] =useState({
    type:false,
    imageSrc:'',
    captionImage:'',
    showImage:false,
});

当改变状态时

setState({type:true});
setState({captionImage:'hellooo'});
setState({imageSrc:link});

并将其发送到另一个组件,该组件中有未定义的, 但是我把 state 写成

const [type, setType] = useState(false);
const [imageSrc, setImageSrc] = useState('');
const [captionImage, setCaptionImage] = useState(false);
const [showImage, setShowImage] = useState(false);

当改变状态时

setType(true);

并将其发送到另一个组件,该组件中没有问题。

【问题讨论】:

    标签: javascript reactjs object state


    【解决方案1】:

    因为在第一种形式中,当您设置新状态而不是像这样传递新的完整对象时:

    {
        type:false,
        imageSrc:'',
        captionImage:'',
        showImage:false,
    }
    

    您正在将您的状态设置为:

    {type:true}
    

    其他的道具都不见了,如果你只想替换你所在州的一个道具(例如type,在保留其他道具的同时,你可以这样做:

    setState({ ...state, type: 'new value' })
    

    【讨论】:

    • 你说的是真的,它可以工作,但状态的值在其他组件中没有改变,初始值为
    • @zahraei 你是如何传递道具的?
    • @Marcos => 传递 props 形式为:{ state.showImage ? : ''" }
    猜你喜欢
    • 2019-08-03
    • 2016-04-03
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多