gpt4 book ai didi

javascript - 如何在 React 生命周期方法中正确分派(dispatch)操作?

转载 作者:行者123 更新时间:2023-12-03 02:13:40 24 4
gpt4 key购买 nike

如何在 React 生命周期方法中正确分派(dispatch)操作?

friend 们大家好我的父组件 (App.jsx) 中有一个名为 checkSession() 的操作。此操作可以帮助我获取用户信息。
App.jsx 如下所示:

class App extends Component {
componentWillMount() {
this.props.checkSession();
}
render() {
if (this.props.auth === null) {
return <div>Loading...</div>;
} else {
return (
<BrowserRouter>
<Route path="/cart" component={Cart} />
</BrowserRouter>
);
}
}
}
const mapStateToProps = ({ auth }) => { auth };
export default connect(mapStateToProps, { checkSession })(App);

如何在 Cart.jsx 组件内正确调度另一个操作。我尝试在 componentWillReceiveProps 方法内分派(dispatch)操作,但它会创建一个无限循环。我的 Cart.jsx 组件如下所示:

import { getCart } from "../../actions"; 

class Cart extends Component {
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.auth) {
this.props.getCart(nextProps.auth.googleId);
} else {
this.props.getCart(null);
}
}
render() {
......some staff
}
}
const mapStateToProps = ({ auth }) => { auth };
export default connect(mapStateToProps, { getCart })(Cart);

我刚刚尝试在 ComponentWillMount 内分派(dispatch)此操作 - 但我的 Prop 尚未准备好,因此出现错误。请帮助我提供任何建议,并对我的英语感到抱歉。

最佳答案

也许您必须在触发调度之前检测 props 是否已更改:

componentWillReceiveProps(nextProps, nextState) {
const currentId = this.props.auth && this.props.auth.googleId;
const nextId = nextProps.auth && nextProps.auth.googleId;
if (currentId !== nextId) {
this.props.getCart(nextProps.auth.googleId);
}
}

关于javascript - 如何在 React 生命周期方法中正确分派(dispatch)操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49446080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com