【问题标题】:How do I properly dispatch actions inside the React Lifecycle Methods?如何在 React 生命周期方法中正确调度操作?
【发布时间】: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


    【解决方案1】:

    也许你必须在触发 dispatch 之前检测 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);
        }
    }
    

    【讨论】:

    • 谢谢,它可以工作,但是当我刷新页面时,此操作 `this.props.getCart(nextProps.auth.googleId)` 不会被执行。由于无限循环,我不能使用componentWillMount。我该如何处理?
    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    相关资源
    最近更新 更多