我的问题是,我有一个容器,在之前加载并再次安装,在通过componentWillMount()
的操作更新状态后,不会更新它的连接状态。
这里是容器中的代码(您可以获得所有完整代码here):
// [...]
interface Params {
method: 'from-definition'|'from-saved';
target: string;
}
interface Props extends RouteComponentProps<Params> {
state: State;
actions: typeof Actions;
}
interface ContainerState {
isActionBarSticky: boolean;
}
class Container extends React.Component<Props, ContainerState> {
private isTicking: boolean;
constructor(props: Props) {
super(props);
this.state = {
isActionBarSticky: true,
};
// [...]
}
public componentWillMount() {
switch (this.props.match.params.method) {
case 'from-definition':
this.props.actions.setQuoteFromDefinitionName(this.props.match.params.target);
break;
case 'from-saved':
this.props.actions.setQuoteFromSavedQuoteTitle(this.props.match.params.target);
break;
}
}
// [...]
public render() {
// [...]
if (this.props.state.quote) {
loadedQuote = this.props.state.quote.sections.map((s) => {
return (
// [...]
);
});
// [...]
}
return (
<Wrapper style={this.state.isActionBarSticky ? {paddingBottom: '56px'} : undefined}>
{loadedQuote}
{actionBar}
</Wrapper>
);
}
// [...]
}
const mapStateToProps = (state: State) => ({
state,
});
const mapDispatchToProps = (dispatch: Dispatch<State>) => ({
actions: bindActionCreators<typeof Actions>(Actions, dispatch)
});
export const QuoteContainer = withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));
所以容器之前已加载,我再次访问同一页面,因此它再次安装。 this.props.actions.setQuoteFromDefinitionName(this.props.match.params.target);
被称为。{/ p>
正如我在Redux DevTools中看到的那样,它正确地更新了状态。
容器按预期在componentWillMount()
之后呈现,但this.props.state.quote
中的状态未更新。为什么会这样?
答案 0 :(得分:4)
来自react docs:在安装发生之前立即调用componentWillMount()。它在render()之前调用,因此在此方法中同步调用setState()不会触发额外的渲染。通常,我们建议使用构造函数()。
避免在此方法中引入任何副作用或订阅。对于这些用例,请改用componentDidMount()。
这是在服务器渲染上调用的唯一生命周期钩子。