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

标签 javascript reactjs redux action react-lifecycle

如何在 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/

相关文章:

javascript - 如何将基于内部状态的 React 应用程序转换为基于 Redux 的应用程序?

javascript - redux-form 中的同名字段

javascript - 无法使用 Angular 的 HttpClient 上传图片

javascript - 整个屏幕变灰,包括滚动条

javascript - 如何通过分析功能跟踪 Ajax 操作

javascript - 我如何添加类名正文向下滚动 react ?

node.js - 如何从 React 提交 multipart/form-data 到 express?

reactjs - Serviceworker 且不能在模块外部使用 import 语句

javascript - 样式组件中的响应式数组

javascript - 如何在下拉列表选择 ReactJS 中更改对象数组的值