场景复现:
react多组件间通讯
在做文章编辑发布的时候,文章各内容均分布于不同的组件,甚至存在于不同的页面,还存在组件销毁问题,想在点击发布的时候拿到其他组件的内容是比较麻烦的
我最初的解决方案
采用dva简易数据流model对全局数据进行管理
- 设立全局model
export default {
namespace: 'write',
state: {
content: '',
title: '',
category: '',
description:'',
isPublic:false,
coverUrl:''
},
- 各组件内同步model状态
if (response.code === 200) {
dispatch({
type: "write/setPostByHand",
payload: {
coverUrl: response.message
}
});
- 最终消费成功后重置全局model
if (response.code===200){
message.success("发表成功")
//清除全局model
dispatch({
type: "write/cleanPostByHand",
})
history.push(`home`)
}else{
message.error("系统错误,请联系小星")
}
后续思路及改进措施:
虽然这种方式成功实现了需求,但是在浏览器刷新的时候还是会造成数据丢失
所以昨晚睡觉的时候我想到是否可以用localstorage存储,这样就不存在数据丢失的问题了(天哪我为什么没有早想到
)