确保在浏览器会话中当前redux状态
在没有第三方图书馆的情况下,在浏览器会议上刷新状态的最佳实践是什么?在触发状态的对象上下载之前,我需要确保数据是最新的。我尝试使用多个使用效果(一个更新数据,一个以触发下载),但状态函数在更新对象之前在Props中呼叫下载。我知道状态是异步设置的,但无法解决此问题。
function DownloadButton(props){
const {selected} = props;
let selectedFile = selected ? props.all.files[selected] : null;
const [downloaded, setDownloaded] = useState(false);
useEffect(() => {
if(selected && downloaded === true){
selectedFile.download();
}
setDownloaded(false);
}, [props.all, downloaded]);
return(
<DownloadButton
onClick={() => {
//trigger refresh of props.all
props.refresh();
//below works if wrapped in setTimeout
setDownloaded(true);
}}
/>
);
}
const mapStateToProps = state => {
return {
all: state.all
}
}
const mapDispatchToProps = dispatch => {
return {
refresh: () => dispatch({type: "GET_ALL"})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DownloadButton);
What is the best practice for refreshing state across browser sessions without a third party library? I need to make sure data is current before triggering a download on an object in state. I have tried using multiple useEffect's (one to update the data, one to trigger the download) but the state function calls the download on the state in props before updating the object. I know state is set asynchronously but haven't been able to resolve this issue.
function DownloadButton(props){
const {selected} = props;
let selectedFile = selected ? props.all.files[selected] : null;
const [downloaded, setDownloaded] = useState(false);
useEffect(() => {
if(selected && downloaded === true){
selectedFile.download();
}
setDownloaded(false);
}, [props.all, downloaded]);
return(
<DownloadButton
onClick={() => {
//trigger refresh of props.all
props.refresh();
//below works if wrapped in setTimeout
setDownloaded(true);
}}
/>
);
}
const mapStateToProps = state => {
return {
all: state.all
}
}
const mapDispatchToProps = dispatch => {
return {
refresh: () => dispatch({type: "GET_ALL"})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DownloadButton);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,该组件与刷新机制有点涉及,所以我将其委派给了Redux Action:
It seems to me that the component is a bit too involved with the refresh mechanism, so I'd delegate that to a redux action instead: