【发布时间】:2018-03-23 09:17:38
【问题描述】:
如何在 React 生命周期方法中正确调度操作?
朋友们好
我的父组件 (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 方法中调度操作,但它会创建一个无限循环。
我的 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 中调度此操作 - 但我的道具尚未准备好,因此出现错误。 请帮我提供任何建议,并为我的英语感到抱歉。
【问题讨论】:
标签: javascript reactjs redux action react-lifecycle