美文网首页让前端飞Web前端之路
react hooks 踩坑记setState之visible

react hooks 踩坑记setState之visible

作者: 嘻哈章鱼小丸子 | 来源:发表于2020-07-20 18:55 被阅读0次

    first,show my code!

    index.jsx:

     const [visible, setVisible] = useState(false);
     <Button type="link" onClick={() => {
                            setRecord(record)
                            setVisible(true)
                        }}>详情</Button>
     {visible ? <Detail visible={visible}
                                    onClose={() => setVisible(false)}
                                    record={record} /> : null}
    

    Detail.jsx:

        useEffect(() => {
        function getDetail() {
            const res = ask("getDetail", {
                params: {
                    times: record.times,
                    id: record.id
                }
            })
            if (res.errorCode === 200) {
                setDetail(res.data);
            } else {
                message.error(res.msg|| '获取详情失败!');
            }
        }
            getDetail();
        }, []);
    

    结果就是:如果第一次请求失败了,errorCode不是200,那详情弹框永远弹不出来。因为visible永远是true,没有改变,function不会重新render
    -_-

    排查了下,果断在报错后设置正确的visible,加上onClose方法:

     else {
                message.error(res.msg|| '获取详情失败!');
                onClose();
            }
    

    成功,在报错状态下也可以正常弹框了!

    总结:使用setState类的hooks一定要正确处理state,尤其是visible这类比较明显的。侧面也体现了react diff能力的强大。

    相关文章

      网友评论

        本文标题:react hooks 踩坑记setState之visible

        本文链接:https://www.haomeiwen.com/subject/aziykktx.html