我有一条路由(使用React-Router)及其呈现的组件。每次打开此路由并创建其组件时,我都需要重置此组件中使用的Redux状态(实际上是一个reducer的状态)的一部分。该reducer在应用程序的其他部分共享,因此我使用Redux状态而不是本地组件的状态。那么,如何在每次创建组件时重置Reducer的状态?我想知道这样做的最佳实践。
我认为,如果我要在componentDidMount方法中分派动作,则先前状态会闪烁一秒钟。
我可以调度动作以重置组件构造函数中某些减速器的状态吗?
有没有更好的方法?我可以以某种方式在connect()函数中设置初始状态,以便每次创建组件时都会重置其状态吗?我检查了文档,但是找不到相应的参数。
答案 0 :(得分:1)
是的,您可以在构造函数中调度动作以更改减速器状态
constructor(prop){
super(prop);
prop.dispatch(action);
}
您可以尝试的另一种方法是设置默认道具,从而无需调用reducer(调度动作)
ButtonComponent.defaultProps = {
message: defaultValue,
};
答案 1 :(得分:0)
我能想到的一种可能的解决方案...
如果可以采用第一种方法,则可以尝试在以重置状态重新呈现组件时停止显示先前的状态。
您将看到prevState的唯一阶段是在初始渲染期间。如何使用实例变量来跟踪渲染计数。
草稿
import React from "react";
import { connect } from "react-redux";
import { add, reset } from "./actions";
class Topics extends React.Component {
renderCount = 0;
componentDidMount() {
// Dispatch actions to reset the redux state
// When the connected props change, component should re-render
this.props.reset();
}
render() {
this.renderCount++;
if (this.renderCount > 1) {
return (
<div>
{this.props.topics.map(topic => (
<h3 id={topic}>{topic}</h3>
))}
</div>
);
} else {
return "Initializing"; // You can return even null
}
}
}
const mapStateToProps = state => ({ topics: state });
const mapDispatchToProps = (dispatch) => {
return {
add(value){
dispatch(add(value));
},
reset(){
dispatch(reset());
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Topics);
这里renderCount
是一个类变量,它在组件render
上保持递增。在第一个渲染上显示一个后备UI,以避免显示以前的状态;在第二个渲染上(由于redux存储更新),您可以显示存储数据。
下面添加了一个工作示例。我还添加了一种避免后备UI的方法。看看是否有帮助。
https://stackblitz.com/edit/react-router-starter-fwxgnl?file=components%2FTopics.js